def ensure_social_user(self,
                           provider,
                           user_id,
                           username,
                           extra_data=None,
                           firstname=None,
                           lastname=None):
        from social.apps.django_app.default.models import UserSocialAuth
        import uuid

        try:
            social_auth = UserSocialAuth.objects.get(provider=provider,
                                                     uid=user_id)
            user = social_auth.user

        except UserSocialAuth.DoesNotExist:
            internal_username = username
            while User.objects.filter(username=internal_username).exists():
                internal_username = username + uuid.uuid4().hex[:16]

            user = User.objects.create(username=internal_username,
                                       first_name=firstname or '',
                                       last_name=lastname or '')

            social_auth = UserSocialAuth(user=user,
                                         provider=provider,
                                         uid=user_id,
                                         extra_data=extra_data or {})
            social_auth.save()

        return user, social_auth
예제 #2
0
def _googleAuth(user):
    google_auth = UserSocialAuth()
    google_auth.user = user
    google_auth.provider = 'google'
    google_auth.uid = user.email
    google_auth.extra_data = '{}'
    return google_auth
예제 #3
0
def get_user_id(auth_data):
    provider = auth_data['provider']
    uid = auth_data['uid']
    logger.debug('uid = {}'.format(uid))
    user_social_auth = UserSocialAuth.get_social_auth(provider, uid)
    if user_social_auth:
        user = YMUser.objects.get(id=user_social_auth.user_id)
    else:
        user = YMUser()
    if 'email' in auth_data:
        user.email = auth_data['email']
    if 'username' in auth_data:
        user.username = auth_data['username']
    if 'first_name' in auth_data:
        user.first_name = auth_data['first_name']
    if 'last_name' in auth_data:
        user.last_name = auth_data['last_name']
    if 'picture' in auth_data:
        user.icon_url = auth_data['picture']
    if 'locale' in auth_data:
        user.locale = auth_data['locale']
    # logger.debug('user save called...')
    user.save()
    if user_social_auth:
        return (user.id, False)
    user_social_auth = UserSocialAuth(user_id=user.id,
                                      provider=provider,
                                      uid=uid,
                                      extra_data=auth_data)
    user_social_auth.save()
    return (user.id, True)
예제 #4
0
    def test__email(self):
        job = running_jobs.pop(0)
        test_project = Project(collab=job["collab_id"], context=uuid4())
        test_project.save()
        test_quota = Quota(project=test_project, platform=job["hardware_platform"],
                           usage=0, limit=1000, units="foo-hours")
        test_quota.save()
        if USE_MOCKS:
            user = User(username="******", email="*****@*****.**")
            user.save()
            sa = UserSocialAuth(user=user, uid=job['user_id'])
            sa.save()

        log = "\n".join(str(x) for x in range(105))
        log_response = self.client.put("/api/v2/log/{}".format(job["id"]),
                                       data=json.dumps({"content": log}),
                                       content_type="application/json")
        self.assertEqual(log_response.status_code, 201)

        job['timestamp_submission'] = job['timestamp_submission'].isoformat()
        job['status'] = "finished"
        job["provenance"]["version"] = 123
        job["resource_usage"] = 23
        job['hardware_config']["resource_allocation_id"] = test_quota.pk
        resource_uri = "/api/v2/queue/{}".format(job["id"])
        response = self.client.put(resource_uri, data=json.dumps(job), content_type="application/json")
        self.assertEqual(response.status_code, 204)

        message = mail.outbox[0]
        self.assertEqual(message.to, ["*****@*****.**"])
        self.assertEqual(message.subject, "[HBP Neuromorphic] job {} finished".format(job["id"]))
        self.assertIn("Job {} finished".format(job["id"]), message.body)
        self.assertIn("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n",
                      message.body)
        self.assertIn("27\n28\n29\n\n.  .  .\n\n35\n36\n37",  # cut at :30 and -70:
                      message.body)
        self.assertIn("95\n96\n97\n98\n99\n100\n101\n102\n103\n104",
                      message.body)
        self.assertIn("https://collab.humanbrainproject.eu/#/collab/{}/nav/{}?state=job.{}".format(job["collab_id"],
                                                                                                   job["provenance"]["collaboratory"]["nav_item"],
                                                                                                   job["id"]),
                      message.body)
예제 #5
0
    def create_links(self):
        """
        Create all needed links to Django and/or UserSocialAuth.
        """
        extra_data = json.loads(self.extra_data)
        username = extra_data.get(
            'lis_person_name_full',
            extra_data.get('lis_person_sourcedid', self.user_id))
        first_name = extra_data.get('lis_person_name_given', '')
        last_name = extra_data.get('lis_person_name_family', '')
        email = extra_data.get('lis_person_contact_email_primary', '').lower()

        defaults = {
            'first_name': first_name,
            'last_name': last_name,
        }

        if email:
            defaults['email'] = email
            social = UserSocialAuth.objects.filter(provider='email',
                                                   uid=email).first()
            if social:
                django_user = social.user
            else:
                django_user = User.objects.filter(email=email).first()
                if not django_user:
                    django_user, created = User.objects.get_or_create(
                        username=username, defaults=defaults)
                social = UserSocialAuth(user=django_user,
                                        provider='email',
                                        uid=email,
                                        extra_data=extra_data)
                social.save()
        else:
            django_user, created = User.objects.get_or_create(
                username=username, defaults=defaults)
        self.django_user = django_user
        self.save()
예제 #6
0
def save_profile(backend,
                 strategy,
                 uid,
                 response={} or object(),
                 details={},
                 *args,
                 **kwargs):
    print('response: ' + str(response))
    print('details: ' + str(details))
    print('args: ' + str(args))
    print('kwargs: ' + str(kwargs))
    user = Account.objects.filter(auth_via=backend.name, social_id=uid).first()
    if user:
        login_user = auth.authenticate(username=details['email'],
                                       password='******')
        social = UserSocialAuth(login_user, uid, backend.name)
        strategy.session_set('email', details['email'])
    else:
        if details['email'] == '':
            raise AuthTokenError('error')

        avatar = '/media/default_avatar.png'

        if response['photo']:
            avatar = response['photo']

        # reg user
        hasher = get_hasher('default')

        if 'bdate' in response and len(response['bdate'].split('.')) != 3:
            date = response['bdate'].split('.')
            date = date[-1] + '.' + date[1] + '.' + date[0]
            try:
                Account.objects.create(password=hasher.encode(
                    '55', hasher.salt()),
                                       email=details['email'],
                                       first_name=details['first_name'],
                                       last_name=details['last_name'],
                                       auth_via=backend.name,
                                       access_token=response['access_token'],
                                       social_id=uid,
                                       avatar=avatar,
                                       sex=response['sex'],
                                       birthday=date)
            except IntegrityError:
                raise AuthMissingParameter
        else:
            try:
                Account.objects.create(password=hasher.encode(
                    '55', hasher.salt()),
                                       email=details['email'],
                                       first_name=details['first_name'],
                                       last_name=details['last_name'],
                                       auth_via=backend.name,
                                       access_token=response['access_token'],
                                       social_id=uid,
                                       avatar=avatar,
                                       sex=response['sex'])
            except IntegrityError:
                raise AuthMissingParameter

        # login user
        login_user = auth.authenticate(username=details['email'],
                                       password='******')
        social = UserSocialAuth(login_user, uid, backend.name)
        strategy.session_set('email', details['email'])

    return {'user': login_user, 'social': social}