Exemple #1
0
def persona_login(request):
    assertion = request.POST.get('assertion', '')
    audience = request.build_absolute_uri('/')
    resp = requests.post('https://verifier.login.persona.org/verify',
                         {'assertion': assertion,
                          'audience': audience})
    if resp.json()['status'] != 'okay':
        return render_authentication_error(request)
    email = resp.json()['email']
    extra_data = resp.json()
    account = SocialAccount(uid=email,
                            provider=PersonaProvider.id,
                            extra_data=extra_data)
    account.user = get_adapter() \
        .populate_new_user(request,
                           account,
                           email=email)
    # TBD: Persona e-mail addresses are verified, so we could check if
    # a matching local user account already exists with an identical
    # verified e-mail address and short-circuit the social login. Then
    # again, this holds for all social providers that guarantee
    # verified e-mail addresses, so if at all, short-circuiting should
    # probably not be handled here...
    login = SocialLogin(account)
    login.state = SocialLogin.state_from_request(request)
    return complete_social_login(request, login)
Exemple #2
0
def persona_login(request):
    assertion = request.POST.get('assertion', '')
    audience = request.build_absolute_uri('/')
    resp = requests.post('https://verifier.login.persona.org/verify', {
        'assertion': assertion,
        'audience': audience
    })
    if resp.json()['status'] != 'okay':
        return render_authentication_error(request)
    email = resp.json()['email']
    extra_data = resp.json()
    account = SocialAccount(uid=email,
                            provider=PersonaProvider.id,
                            extra_data=extra_data)
    account.user = get_adapter() \
        .populate_new_user(request,
                           account,
                           email=email)
    # TBD: Persona e-mail addresses are verified, so we could check if
    # a matching local user account already exists with an identical
    # verified e-mail address and short-circuit the social login. Then
    # again, this holds for all social providers that guarantee
    # verified e-mail addresses, so if at all, short-circuiting should
    # probably not be handled here...
    login = SocialLogin(account)
    login.state = SocialLogin.state_from_request(request)
    return complete_social_login(request, login)
Exemple #3
0
 def complete_login(self, request, app, token, **kwargs):
     resp = requests.get(self.profile_url,
                         params={ 'access_token': token.token,
                                  'alt': 'json' })
     extra_data = resp.json()
     # extra_data is something of the form:
     #
     # {u'family_name': u'Penners', u'name': u'Raymond Penners',
     #  u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg',
     #  u'locale': u'nl', u'gender': u'male',
     #  u'email': u'*****@*****.**',
     #  u'link': u'https://plus.google.com/108204268033311374519',
     #  u'given_name': u'Raymond', u'id': u'108204268033311374519',
     #  u'verified_email': True}
     #
     # TODO: We could use verified_email to bypass allauth email verification
     uid = str(extra_data['id'])
     account = SocialAccount(extra_data=extra_data,
                             uid=uid,
                             provider=self.provider_id)
     user = get_adapter() \
         .populate_new_user(request,
                            account,
                            email=extra_data.get('email'),
                            last_name=extra_data.get('family_name'),
                            first_name=extra_data.get('given_name'))
     account.user = user
     email_addresses = []
     email = user_email(user)
     if email and extra_data.get('verified_email'):
         email_addresses.append(EmailAddress(email=email,
                                             verified=True,
                                             primary=True))
     return SocialLogin(account,
                        email_addresses=email_addresses)
Exemple #4
0
 def complete_login(self, request, app, token, **kwargs):
     resp = requests.get(self.profile_url,
                         params={
                             'access_token': token.token,
                             'alt': 'json'
                         })
     extra_data = resp.json()
     # extra_data is something of the form:
     #
     # {u'family_name': u'Penners', u'name': u'Raymond Penners',
     #  u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg',
     #  u'locale': u'nl', u'gender': u'male',
     #  u'email': u'*****@*****.**',
     #  u'link': u'https://plus.google.com/108204268033311374519',
     #  u'given_name': u'Raymond', u'id': u'108204268033311374519',
     #  u'verified_email': True}
     #
     # TODO: We could use verified_email to bypass allauth email verification
     uid = str(extra_data['id'])
     account = SocialAccount(extra_data=extra_data,
                             uid=uid,
                             provider=self.provider_id)
     user = get_adapter() \
         .populate_new_user(request,
                            account,
                            email=extra_data.get('email'),
                            last_name=extra_data.get('family_name'),
                            first_name=extra_data.get('given_name'))
     account.user = user
     email_addresses = []
     email = user_email(user)
     if email and extra_data.get('verified_email'):
         email_addresses.append(
             EmailAddress(email=email, verified=True, primary=True))
     return SocialLogin(account, email_addresses=email_addresses)
def get_or_create_user(payload, oidc=False):
    user_id = payload.get('sub')
    if not user_id:
        msg = _('Invalid payload. sub missing')
        raise ValueError(msg)

    # django-helusers uses UUID as the primary key for the user
    # If the incoming token does not have UUID in the sub field,
    # we must synthesize one
    if not is_valid_uuid(user_id):
        # Maybe we have an Azure pairwise ID? Check for Azure tenant ID
        # in token and use that as UUID namespace if available
        namespace = payload.get('tid')
        user_id = convert_to_uuid(user_id, namespace)

    try_again = False
    try:
        user = _try_create_or_update(user_id, payload, oidc)
    except IntegrityError:
        # If we get an integrity error, it probably meant a race
        # condition with another process. Another attempt should
        # succeed.
        try_again = True
    if try_again:
        # We try again without catching exceptions this time.
        user = _try_create_or_update(user_id, payload, oidc)

    # If allauth.socialaccount is installed, create the SocialAcount
    # that corresponds to this user. Otherwise logins through
    # allauth will not work for the user later on.
    if 'allauth.socialaccount' in settings.INSTALLED_APPS:
        from allauth.socialaccount.models import SocialAccount, EmailAddress

        if oidc:
            provider_name = 'helsinki_oidc'
        else:
            provider_name = 'helsinki'
        args = {'provider': provider_name, 'uid': user_id}
        try:
            account = SocialAccount.objects.get(**args)
            assert account.user_id == user.id
        except SocialAccount.DoesNotExist:
            account = SocialAccount(**args)
            account.extra_data = payload
            account.user = user
            account.save()

            try:
                email = EmailAddress.objects.get(email__iexact=user.email)
                assert email.user == user
            except EmailAddress.DoesNotExist:
                email = EmailAddress(email=user.email.lower(), primary=True,
                                     user=user, verified=True)
                email.save()

    return user
Exemple #6
0
    def dispatch(self, request, *args, **kwargs):
        """
        Override allauth's dispatch method to transparently just login if
        the email already exists.  By doing this in dispatch, we can check for
        existing email, and if a match is found, associate the social account
        with that user and log them in.  Allauth does not provide a mechanism
        for doing precisely this.
        """
        ret = super().dispatch(request, *args, **kwargs)
        # By calling super().dispatch first, we set self.sociallogin
        try:
            # The email is contained in sociallogin.account.extra_data
            extra_data = self.sociallogin.account.extra_data
        except AttributeError:
            return ret
        # extract email
        email = extra_data["email"]
        if email_address_exists(email):
            # check that email exists.
            # If the email does exist, and there is a social account associated
            # with the user, then we don't have to do anything else
            if not self.sociallogin.is_existing:
                # However, if the email exists, and there isn't a social
                # account associated with that user, we need to associate the
                # social account
                # Allauth would perform this as part of the form.save step, but
                # we are entirely bypassing the form.
                account_emailaddress = EmailAddress.objects.get(email=email)
                self.sociallogin.user = account_emailaddress.user
                # allauth (and us) uses the sociallogin user as a temporary
                # holding space, and it already is largely filled out by
                # allauth; we just need to set the user.
                # This model does not get saved to the database.

                # We're trusting social provided emails already
                account_emailaddress.verified = True
                account_emailaddress.save()
                if not SocialAccount.objects.filter(
                        uid=self.sociallogin.account.uid,
                        provider=self.sociallogin.account.provider,
                ).exists():
                    # just to be on the safe side, double check that the account
                    # does not exist in the database and that the provider is
                    # valid.
                    socialaccount = SocialAccount()
                    socialaccount.uid = self.sociallogin.account.uid
                    socialaccount.provider = self.sociallogin.account.provider
                    socialaccount.extra_data = extra_data
                    socialaccount.user = self.sociallogin.user
                    socialaccount.save()
                return complete_social_login(request, self.sociallogin)

        return ret
def _process_signup(request, data, account):
    # If email is specified, check for duplicate and if so, no auto signup.
    auto_signup = app_settings.AUTO_SIGNUP
    email = data.get('email')
    if auto_signup:
        # Let's check if auto_signup is really possible...
        if email:
            if account_settings.UNIQUE_EMAIL:
                if email_address_exists(email):
                    # Oops, another user already has this address.  We
                    # cannot simply connect this social account to the
                    # existing user. Reason is that the email adress may
                    # not be verified, meaning, the user may be a hacker
                    # that has added your email address to his account in
                    # the hope that you fall in his trap.  We cannot check
                    # on 'email_address.verified' either, because
                    # 'email_address' is not guaranteed to be verified.
                    auto_signup = False
                    # FIXME: We redirect to signup form -- user will
                    # see email address conflict only after posting
                    # whereas we detected it here already.
        elif account_settings.EMAIL_REQUIRED:
            # Nope, email is required and we don't have it yet...
            auto_signup = False
    if not auto_signup:
        request.session['socialaccount_signup'] = dict(data=data,
                                                       account=account)
        url = reverse('socialaccount_signup')
        next = request.REQUEST.get('next')
        if next:
            url = url + '?' + urlencode(dict(next=next))
        ret = HttpResponseRedirect(url)
    else:
        # FIXME: There is some duplication of logic inhere 
        # (create user, send email, in active etc..)
        username = generate_unique_username \
            (data.get('username', email or 'user'))
        u = User(username=username,
                 email=email or '',
                 last_name = data.get('last_name', '')[0:User._meta.get_field('last_name').max_length],
                 first_name = data.get('first_name', '')[0:User._meta.get_field('first_name').max_length])
        u.set_unusable_password()
        u.is_active = not account_settings.EMAIL_VERIFICATION
        u.save()
        accountbase = SocialAccount()
        accountbase.user = u
        accountbase.save()
        account.base = accountbase
        account.sync(data)
        send_email_confirmation(u, request=request)
        ret = complete_social_signup(request, u, account)
    return ret
Exemple #8
0
 def complete_login(self, request, app, token):
     client = VimeoAPI(request, app.client_id, app.secret,
                       self.request_token_url)
     extra_data = client.get_user_info()
     uid = extra_data['id']
     account = SocialAccount(provider=self.provider_id,
                             extra_data=extra_data,
                             uid=uid)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            name=extra_data.get('display_name'),
                            username=extra_data.get('username'))
     return SocialLogin(account)
Exemple #9
0
 def complete_login(self, request, app, token):
     client = TwitterAPI(request, app.client_id, app.secret,
                         self.request_token_url)
     extra_data = client.get_user_info()
     uid = extra_data['id']
     account = SocialAccount(uid=uid,
                             provider=TwitterProvider.id,
                             extra_data=extra_data)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            username=extra_data.get('screen_name'),
                            name=extra_data.get('name'))
     return SocialLogin(account)
Exemple #10
0
 def complete_login(self, request, app, token):
     client = VimeoAPI(request, app.client_id, app.secret,
                       self.request_token_url)
     extra_data = client.get_user_info()
     uid = extra_data['id']
     account = SocialAccount(provider=self.provider_id,
                             extra_data=extra_data,
                             uid=uid)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            name=extra_data.get('display_name'),
                            username=extra_data.get('username'))
     return SocialLogin(account)
Exemple #11
0
 def complete_login(self, request, app, token, **kwargs):
     resp = requests.get(self.profile_url,
                         params={'access_token': token.token})
     extra_data = resp.json()['data']
     uid = str(extra_data['login'])
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter().populate_new_user(
         request,
         account,
         username=extra_data['login'],
         name=extra_data.get('full_name'))
     return SocialLogin(account)
Exemple #12
0
def callback(request):
    client = _openid_consumer(request)
    response = client.complete(dict(request.REQUEST.items()), request.build_absolute_uri(request.path))
    if response.status == consumer.SUCCESS:
        account = SocialAccount(uid=response.identity_url, provider=OpenIDProvider.id, extra_data={})
        account.user = get_adapter().populate_new_user(request, account, email=_get_email_from_response(response))
        login = SocialLogin(account)
        login.state = SocialLogin.unstash_state(request)
        ret = complete_social_login(request, login)
    elif response.status == consumer.CANCEL:
        ret = HttpResponseRedirect(reverse("socialaccount_login_cancelled"))
    else:
        ret = render_authentication_error(request)
    return ret
def get_or_create_user(payload, oidc=False):
    user_id = payload.get('sub')
    if not user_id:
        msg = _('Invalid payload.')
        raise exceptions.AuthenticationFailed(msg)

    try_again = False
    try:
        user = _try_create_or_update(user_id, payload, oidc)
    except IntegrityError:
        # If we get an integrity error, it probably meant a race
        # condition with another process. Another attempt should
        # succeed.
        try_again = True
    if try_again:
        # We try again without catching exceptions this time.
        user = _try_create_or_update(user_id, payload, oidc)

    # If allauth.socialaccount is installed, create the SocialAcount
    # that corresponds to this user. Otherwise logins through
    # allauth will not work for the user later on.
    if 'allauth.socialaccount' in settings.INSTALLED_APPS:
        from allauth.socialaccount.models import SocialAccount, EmailAddress

        if oidc:
            provider_name = 'helsinki_oidc'
        else:
            provider_name = 'helsinki'
        args = {'provider': provider_name, 'uid': user_id}
        try:
            account = SocialAccount.objects.get(**args)
            assert account.user_id == user.id
        except SocialAccount.DoesNotExist:
            account = SocialAccount(**args)
            account.extra_data = payload
            account.user = user
            account.save()

            try:
                email = EmailAddress.objects.get(email__iexact=user.email)
                assert email.user == user
            except EmailAddress.DoesNotExist:
                email = EmailAddress(email=user.email.lower(),
                                     primary=True,
                                     user=user,
                                     verified=True)
                email.save()

    return user
Exemple #14
0
 def complete_login(self, request, app, token, **kwargs):
     resp = requests.get(self.profile_url,
                         params={'oauth_token': token.token})
     extra_data = resp.json()
     uid = str(extra_data['id'])
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            name=extra_data.get('full_name'),
                            username=extra_data.get('username'),
                            email=extra_data.get('email'))
     return SocialLogin(account)
Exemple #15
0
 def complete_login(self, request, app, token, **kwargs):
     resp = requests.get(self.profile_url,
                         params={'oauth_token': token.token})
     extra_data = resp.json()
     uid = str(extra_data['_id'])
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            username=extra_data.get('display_name'),
                            name=extra_data.get('name'),
                            email=extra_data.get('email'))
     return SocialLogin(account)
Exemple #16
0
 def complete_login(self, request, app, token, **kwargs):
     uid = kwargs.get('response', {}).get('uid')
     resp = requests.get(self.profile_url,
                         params={'access_token': token.token,
                                 'uid': uid})
     extra_data = resp.json()
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            username=extra_data.get('screen_name'),
                            name=extra_data.get('name'))
     return SocialLogin(account)
Exemple #17
0
 def complete_login(self, request, app, token):
     client = LinkedInAPI(request, app.client_id, app.secret,
                          self.request_token_url)
     extra_data = client.get_user_info()
     uid = extra_data['id']
     account = SocialAccount(provider=self.provider_id,
                             extra_data=extra_data,
                             uid=uid)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            email=extra_data.get('email-address'),
                            first_name=extra_data.get('first-name'),
                            last_name=extra_data.get('last-name'))
     return SocialLogin(account)
Exemple #18
0
 def complete_login(self, request, app, token):
     client = LinkedInAPI(request, app.client_id, app.secret,
                          self.request_token_url)
     extra_data = client.get_user_info()
     uid = extra_data['id']
     account = SocialAccount(provider=self.provider_id,
                             extra_data=extra_data,
                             uid=uid)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            email=extra_data.get('email-address'),
                            first_name=extra_data.get('first-name'),
                            last_name=extra_data.get('last-name'))
     return SocialLogin(account)
Exemple #19
0
def fb_complete_login(request, app, token):
    resp = requests.get('https://graph.facebook.com/me',
                        params={'access_token': token.token})
    extra_data = resp.json()
    uid = extra_data['id']
    account = SocialAccount(uid=uid,
                            provider=FacebookProvider.id,
                            extra_data=extra_data)
    account.user = get_adapter() \
        .populate_new_user(request,
                           account,
                           email=extra_data.get('email'),
                           username=extra_data.get('username'),
                           first_name=extra_data.get('first_name'),
                           last_name=extra_data.get('last_name'))
    return SocialLogin(account)
Exemple #20
0
def fb_complete_login(request, app, token):
    resp = requests.get('https://graph.facebook.com/me',
                        params={'access_token': token.token})
    extra_data = resp.json()
    uid = extra_data['id']
    account = SocialAccount(uid=uid,
                            provider=FacebookProvider.id,
                            extra_data=extra_data)
    account.user = get_adapter() \
        .populate_new_user(request,
                           account,
                           email=extra_data.get('email'),
                           username=extra_data.get('username'),
                           first_name=extra_data.get('first_name'),
                           last_name=extra_data.get('last_name'))
    return SocialLogin(account)
def get_or_create_user(payload, oidc=False):
    user_id = payload.get('sub')
    if not user_id:
        msg = _('Invalid payload.')
        raise exceptions.AuthenticationFailed(msg)

    user_model = get_user_model()

    with transaction.atomic():
        try:
            user = user_model.objects.select_for_update().get(uuid=user_id)
        except user_model.DoesNotExist:
            user = user_model(uuid=user_id)
            user.set_unusable_password()
        update_user(user, payload, oidc)

    # If allauth.socialaccount is installed, create the SocialAcount
    # that corresponds to this user. Otherwise logins through
    # allauth will not work for the user later on.
    if 'allauth.socialaccount' in settings.INSTALLED_APPS:
        from allauth.socialaccount.models import SocialAccount, EmailAddress

        if oidc:
            provider_name = 'helsinki_oidc'
        else:
            provider_name = 'helsinki'
        args = {'provider': provider_name, 'uid': user_id}
        try:
            account = SocialAccount.objects.get(**args)
            assert account.user_id == user.id
        except SocialAccount.DoesNotExist:
            account = SocialAccount(**args)
            account.extra_data = payload
            account.user = user
            account.save()

            try:
                email = EmailAddress.objects.get(email__iexact=user.email)
                assert email.user == user
            except EmailAddress.DoesNotExist:
                email = EmailAddress(email=user.email.lower(),
                                     primary=True,
                                     user=user,
                                     verified=True)
                email.save()

    return user
def get_or_create_user(payload, oidc=False):
    user_id = payload.get('sub')
    if not user_id:
        msg = _('Invalid payload.')
        raise exceptions.AuthenticationFailed(msg)

    try_again = False
    try:
        user = _try_create_or_update(user_id, payload, oidc)
    except IntegrityError:
        # If we get an integrity error, it probably meant a race
        # condition with another process. Another attempt should
        # succeed.
        try_again = True
    if try_again:
        # We try again without catching exceptions this time.
        user = _try_create_or_update(user_id, payload, oidc)

    # If allauth.socialaccount is installed, create the SocialAcount
    # that corresponds to this user. Otherwise logins through
    # allauth will not work for the user later on.
    if 'allauth.socialaccount' in settings.INSTALLED_APPS:
        from allauth.socialaccount.models import SocialAccount, EmailAddress

        if oidc:
            provider_name = 'helsinki_oidc'
        else:
            provider_name = 'helsinki'
        args = {'provider': provider_name, 'uid': user_id}
        try:
            account = SocialAccount.objects.get(**args)
            assert account.user_id == user.id
        except SocialAccount.DoesNotExist:
            account = SocialAccount(**args)
            account.extra_data = payload
            account.user = user
            account.save()

            try:
                email = EmailAddress.objects.get(email__iexact=user.email)
                assert email.user == user
            except EmailAddress.DoesNotExist:
                email = EmailAddress(email=user.email.lower(), primary=True,
                                     user=user, verified=True)
                email.save()

    return user
Exemple #23
0
 def complete_login(self, request, app, token, **kwargs):
     uid = kwargs.get('response', {}).get('uid')
     resp = requests.get(self.profile_url,
                         params={
                             'access_token': token.token,
                             'uid': uid
                         })
     extra_data = resp.json()
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            username=extra_data.get('screen_name'),
                            name=extra_data.get('name'))
     return SocialLogin(account)
Exemple #24
0
 def complete_login(self, request, app, token, **kwargs):
     uid = kwargs['response']['user_id']
     resp = requests.get(self.profile_url,
                         params={'access_token': token.token,
                                 'fields': ','.join(USER_FIELDS),
                                 'user_ids': uid})
     resp.raise_for_status()
     extra_data = resp.json()['response'][0]
     account = SocialAccount(extra_data=extra_data,
                             uid=str(uid),
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            last_name=extra_data.get('family_name'),
                            username=extra_data.get('screen_name'),
                            first_name=extra_data.get('given_name'))
     return SocialLogin(account)
Exemple #25
0
 def complete_login(self, request, app, token, **kwargs):
     provider = registry.by_id(app.provider)
     site = provider.get_site()
     resp = requests.get(self.profile_url,
                         params={'access_token': token.token,
                                 'key': app.key,
                                 'site': site})
     extra_data = resp.json()['items'][0]
     # `user_id` varies if you use the same account for
     # e.g. StackOverflow and ServerFault. Therefore, we pick
     # `account_id`.
     uid = str(extra_data['account_id'])
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            username=extra_data.get('display_name'))
     return SocialLogin(account)
Exemple #26
0
def callback(request):
    client = _openid_consumer(request)
    response = client.complete(dict(request.REQUEST.items()),
                               request.build_absolute_uri(request.path))
    if response.status == consumer.SUCCESS:
        account = SocialAccount(uid=response.identity_url,
                                provider=OpenIDProvider.id,
                                extra_data={})
        account.user = get_adapter() \
            .populate_new_user(request,
                               account,
                               email=_get_email_from_response(response))
        login = SocialLogin(account)
        login.state = SocialLogin.unstash_state(request)
        ret = complete_social_login(request, login)
    elif response.status == consumer.CANCEL:
        ret = HttpResponseRedirect(reverse('socialaccount_login_cancelled'))
    else:
        ret = render_authentication_error(request)
    return ret
Exemple #27
0
 def complete_login(self, request, app, token, **kwargs):
     provider = registry.by_id(app.provider)
     site = provider.get_site()
     resp = requests.get(self.profile_url,
                         params={
                             'access_token': token.token,
                             'key': app.key,
                             'site': site
                         })
     extra_data = resp.json()['items'][0]
     # `user_id` varies if you use the same account for
     # e.g. StackOverflow and ServerFault. Therefore, we pick
     # `account_id`.
     uid = str(extra_data['account_id'])
     account = SocialAccount(uid=uid,
                             extra_data=extra_data,
                             provider=self.provider_id)
     account.user = get_adapter() \
         .populate_new_user(request,
                            account,
                            username=extra_data.get('display_name'))
     return SocialLogin(account)
Exemple #28
0
def register_user(request):
    try:
        if request.method == 'POST':
            req_body = json.loads(request.body.decode())

            UserModel = get_user_model()
            user = UserModel.objects.get(
                auth0_identifier=req_body['auth0_identifier'])

            user.first_name = req_body['first_name']
            user.last_name = req_body['last_name']
            user.username = req_body['username']
            user.email = req_body['email']
            password = request.user.auth0_identifier.split('.')[1]
            user.set_password(password)
            user.save()

            new_userprofile = UserProfile.objects.create(
                address=req_body["address"], user=user)
            new_userprofile.save()

            # email = req_body['email']
            authenticated_user = authenticate(
                auth0_identifier=req_body['auth0_identifier'],
                password=password)

            if authenticated_user is not None:
                remote_authenticated_user = request.successful_authenticator.authenticate(
                    request)

                if remote_authenticated_user is not None:
                    management_api_token_endpoint = management_api_oath_endpoint(
                        AUTH0_DOMAIN)
                    management_api_token = json.loads(
                        management_api_token_endpoint)
                    management_api_jwt = management_api_token['access_token']
                    management_api_user = get_management_api_user(
                        AUTH0_DOMAIN, management_api_jwt, req_body['uid'])

                    token = TokenModel.objects.create(
                        user=remote_authenticated_user[0])
                    key = token.key

                    extra_data = req_body['extra_data']
                    extra_data['access_token'] = remote_authenticated_user[1]
                    id_token = json.loads(req_body['id_token'])
                    extra_data['id_token__raw'] = id_token['__raw']
                    nonce = id_token['nonce']
                    identities = management_api_user.get('identities')[0]
                    provider = identities.get('provider')

                    # The 'connection' in the auth0 returned result
                    assoc_type = identities.get('connection')
                    exp = id_token['exp']
                    iat = id_token['iat']

                    backend_data = backends(request)
                    user_current_backend = authenticated_user.backend

                    #auth0_backend = backend_data['backends']['backends'][1]
                    #openId_backend = backend_data['backends']['backends'][0]
                    #associated_backends = backend_data['backends'].get('associated')

                    # return csrf token for POST form. side effect is have @csrf_protect
                    csrf = req_body[
                        'csrf_token'] if 'csrf_token' in req_body and req_body[
                            'csrf_token'] else get_token(request)

                    auth0_user_logs = retrieve_user_logs(
                        AUTH0_DOMAIN, management_api_jwt, req_body['uid'])

                    seacft = [
                        l for l in auth0_user_logs if l['type'] == 'seacft'
                    ]
                    seacft_details = seacft[0].get('details')
                    code = seacft_details.get('code')

                    # ss = [l for l in auth0_user_logs if l['type'] == 'ss']
                    # ss_details = ss[0].get('details')
                    # transaction = ss_details['body']['transaction']

                    # associate_user('openid', social_user.uid, authenticated_user, social_user)
                    social_user = remote_authenticated_user[
                        0].social_auth.get_or_create(
                            user_id=remote_authenticated_user[0].id,
                            provider=provider,
                            extra_data=extra_data,
                            uid=req_body['auth0_identifier'].replace(".", "|"))
                    # is_association = Association.objects.filter(server_url=AUTH0_OPEN_ID_SERVER_URL, handle=handle).exists()

                    if Association.objects.filter(
                            server_url=AUTH0_OPEN_ID_SERVER_URL,
                            handle=nonce).exists():
                        user_association = Association.objects.get(
                            server_url=AUTH0_OPEN_ID_SERVER_URL, handle=nonce)
                    else:
                        user_association = Association.objects.create(
                            server_url=AUTH0_OPEN_ID_SERVER_URL,
                            handle=nonce,
                            secret=code,
                            issued=iat,
                            lifetime=exp,
                            assoc_type=assoc_type)

                    social_account = SocialAccount()
                    social_account.user = remote_authenticated_user[0]
                    social_account.uid = req_body['uid']
                    social_account.provider = provider
                    social_account.extra_data = management_api_user
                    social_account.save()

                    account_email = EmailAddress.objects.get_or_create(
                        user=social_account.user,
                        email=authenticated_user.email,
                        verified=True,
                        primary=True)

                    Nonce.objects.create(server_url=AUTH0_OPEN_ID_SERVER_URL,
                                         timestamp=iat,
                                         salt=nonce)
                    Code.objects.create(email=account_email[0],
                                        code=code,
                                        verified=True)

                    social_app = SocialApp.objects.get_or_create(
                        provider=provider,
                        name="Quantum Coasters",
                        secret=SOCIAL_AUTH_AUTH0_SECRET,
                        client_id=AUTH0_CLIENT_ID,
                        key=SOCIAL_AUTH_AUTH0_KEY)

                    time_now = datetime.datetime.now()
                    expires_at = time_now + datetime.timedelta(0, exp)
                    # time = expires_at.time()

                    social_token = SocialToken.objects.create(
                        app_id=social_app[0].id,
                        account_id=social_account.id,
                        token=id_token,
                        token_secret=id_token['__raw'],
                        expires_at=expires_at)

                    # Changed from user to authenticated_user
                    login(request,
                          social_user[0].user,
                          backend='quantumapi.auth0_backend.Auth0')

                    current_user_session = request.session
                    is_session = Session.objects.filter(
                        session_key=current_user_session.session_key).exists()

                    if is_session:
                        session = Session.objects.get(
                            session_key=current_user_session.session_key)
                    else:
                        session = Session.objects.create(
                            user=authenticated_user)
                        # session.save()

                    EmailConfirmation.objects.get_or_create(
                        email_address=account_email[0],
                        key=session.session_key,
                        sent=datetime.datetime.now())

                    # Turning into Set then back to List to filter out Duplicates (#ToDo-not needed.)
                    social_app_to_list = list(social_app)
                    social_app_data = social_app_to_list[0]

                    auth_user = {
                        "valid": True,
                        "id": user.id,
                        "first_name": user.first_name,
                        "last_name": user.last_name,
                        "email": user.email,
                        "username": user.username,
                        "is_staff": user.is_staff,
                        "auth0_identifier": user.auth0_identifier,
                        "QuantumToken": key,
                        "session": session.session_key,
                        'csrf': csrf,
                        'user_social_auth_id': social_user[0].id,
                        'account_email_id': account_email[0].id,
                        'management_user': management_api_user,
                        'social_account_id': social_account.id,
                        'social_app_id': social_app_data.id,
                        'social_app_name': social_app_data.name,
                        "social_token_id": social_token.id,
                        'association_id': user_association.id,
                        'email_confirmation': True,
                        'user_profile_id': new_userprofile.id,
                    }

                    data = json.dumps({"DjangoUser": auth_user})
                    return HttpResponse(data, content_type='application/json')
                else:
                    error = "Remote authentication failed. Remote Authenticated User was None."
                    data = json.dumps({"Remote Authentication Error": error})
                    return HttpResponse(data, content_type='application/json')
            else:
                error = "Authentication failed. Authenticated User was None."
                data = json.dumps({"Authentication Error": error})
                return HttpResponse(data, content_type='application/json')

    except Exception as ex:
        return Response(ex.args, content_type='application/json')