Пример #1
0
    def setUp(self):
        self.user = User.objects.create_user('jaytest', '*****@*****.**',
                                             'password123.')
        self.token = jwt_encode(self.user)

        self.user2 = User.objects.create_user('jaytest2',
                                              '*****@*****.**',
                                              'password123.')
        self.token2 = jwt_encode(self.user2)
Пример #2
0
    def test_user_professional_iban_swift_to_null_invalid(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)

        data = {
            "first_name": "Aurora",
            "last_name": "Barrios",
            "profile": {
                "phone": "+34661661662",
                "picture": "",
                "type": "PRO",
                "iban_bank_account": "",
                "swift_bank_account": "",
                "documents": ["http://www.facebook.com/", "http://www.google.es"],
                "city": [598]
            },
            "new_zones": [1],
            "new_services": [1, 3]
        }

        client = APIClient()
        response = client.patch('/api/1.0/user/', data=data, format='json',
                                HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data.get('profile').get('non_field_errors')[0],
                         _("Must include iban and swift account number."))
Пример #3
0
    def perform_create(self, serializer):
        validated_data = self.request.data
        user = serializer.save(self.request)
        if getattr(settings, 'REST_USE_JWT', False):
            self.token = jwt_encode(user)
        else:
            create_token(self.token_model, user, serializer)

        complete_signup(self.request._request, user,
                        allauth_settings.EMAIL_VERIFICATION, None)

        subject_data = validated_data.pop('subject')
        activity_data = validated_data.pop('activity')
        regions_data = validated_data.pop('region')

        for data in regions_data:
            region = Region.objects.get(city=data['city'], town=data['town'])
            user.region.add(region)

        for data in activity_data:
            activity = Activity.objects.get(id=data['id'])
            user.activity.add(activity)

        for data in subject_data:
            subject = Subject.objects.get(id=data['id'])
            user.subject.add(subject)
        return user
Пример #4
0
    def test_user_ok(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)

        client = APIClient()
        response = client.get('/api/1.0/user/', format='json', HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
    def test_token_verify(self, client, user, faker):
        freezer = freeze_time('2018-01-01 00:00:00')
        payloads = {}
        response = client.post(self.token_verify_url, data=payloads)
        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert self.token_field in response.data
        assert response.data.get(
            self.token_field) == ['This field is required.']

        payloads = {self.token_field: faker.uuid4()}
        response = client.post(self.token_verify_url, data=payloads)
        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert self.non_field_errors_field in response.data
        assert response.data.get(
            self.non_field_errors_field) == ['Error decoding signature.']

        freezer.start()
        valid_token = jwt_encode(user)
        payloads = {self.token_field: valid_token}
        response = client.post(self.token_verify_url, data=payloads)
        assert response.status_code == status.HTTP_200_OK
        assert len(response.data) == 1
        assert response.data.get(self.token_field) == valid_token
        freezer.stop()

        response = client.post(self.token_verify_url, data=payloads)
        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert self.non_field_errors_field in response.data
        assert response.data.get(
            self.non_field_errors_field) == ['Signature has expired.']
Пример #6
0
    def get_login_redirect_url(self, request):
        next_url = request.session.get('next')
        del request.session['next']

        if next_url:
            localhost = re.compile('localhost')
            token = jwt_encode(request.user)

            if localhost.search(next_url):
                path = 'http://localhost:8080/auth/{}'.format(token)
            else:
                try:
                    detail_url = get_tld(next_url, as_object=True)
                    if detail_url.subdomain in ['tower', 'local.tower']:
                        path = '{}://{}.{}/auth/{}'.format(
                            detail_url.parsed_url.scheme, detail_url.subdomain,
                            detail_url.fld, token)
                    else:
                        path = next_url
                except:
                    path = next_url
        else:
            path = settings.LOGIN_REDIRECT_URL

        return path.format(username=request.user.username)
Пример #7
0
 def partial_update(self, request, pk=None):
     super(UserProfileViewSet, self).partial_update(request, pk)
     try:
         obj = get_object_or_404(UserProfile, pk=pk)
     except:
         raise serializers.ValidationError(str(_(u"Invalid primary key data")))
     if int(pk) is int(request.user.profile.pk) or request.user.is_staff:
         validated_data = request.data
         profile = self.get_object()
         cover_image = validated_data.get('cover_image', None)
         profile_image = validated_data.get('profile_image', None)
         latitude = validated_data.get('latitude', None)
         longitude = validated_data.get('longitude', None)
         if cover_image is not None:
             profile.cover_image = UploadedFile.objects.get(id=cover_image)
         if profile_image is not None:
             profile.profile_image = UploadedFile.objects.get(id=profile_image)
         if latitude is not None and longitude is not None:
             profile.location = profile.get_location(latitude, longitude)
         profile.save()
         serializer = self.get_serializer(data=request.data, context={'request': request}, partial=True)
         if serializer.is_valid():
             data = {'user': profile.user, 'token': jwt_encode(profile.user)}
             return Response(LBCJWTTokenSerializer(data).data)
         else:
             return Response({"error": serializer.errors})
     else:
         raise serializers.ValidationError(u"You can't alter other user's account information. Nice try though")
Пример #8
0
    def test_user_professional_sent_documents_to_null(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)

        data = {
            "first_name": "Aurora",
            "last_name": "Barrios",
            "profile": {
                "phone": "+34661661662",
                "picture": "",
                "type": "PRO",
                "iban_bank_account": "ES5221003179712200170953",
                "swift_bank_account": "CAGLESMMCOP",
                "documents": [],
                "city": [598]
            },
            "new_zones": [1],
            "new_services": [1, 3]
        }

        client = APIClient()
        response = client.patch('/api/1.0/user/', data=data, format='json',
                                HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data.get('profile').get('non_field_errors')[0],
                         _("Must include one document at least"))
Пример #9
0
    def login(self):
        self.user = self.serializer.validated_data['user']

        if self.user.get_has_two_factor():
            # Check if we have a backup code in request.data
            if 'backup_code' in self.serializer.validated_data and self.serializer.validated_data['backup_code'] != '' and not self.serializer.validated_data['backup_code'] is None:
                match_code = None
                codes = TwoFactorBackupCode.objects.filter(user=self.user)
                for code in codes:
                    if self.serializer.validated_data['backup_code'] == code.code:
                        match_code = code
                if not match_code:
                    raise InvalidBackupCode()
                else:
                    match_code.delete()
            # Verify 2FA code
            elif self.serializer.validated_data['two_factor_token'] != '' and not self.serializer.validated_data['two_factor_token'] is None:
                totp = TOTP(TwoFactorConfiguration.objects.get(user=self.user).totp_key)
                print(self.serializer.validated_data['two_factor_token'])
                print(totp.now())
                if not totp.verify(self.serializer.validated_data['two_factor_token']):
                    raise TwoFactorInvalid()
            # Raise Exception if code is not valid
            else:
                raise TwoFactorRequired()

        if getattr(settings, 'REST_USE_JWT', False):
            self.token = jwt_encode(self.user)
        else:
            self.token = create_token(self.token_model, self.user,
                                      self.serializer)

        if getattr(settings, 'REST_SESSION_LOGIN', True):
            self.process_login()
Пример #10
0
    def test_user_professional_sent_invalid_service(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)

        data = {
            "first_name": "Aurora",
            "last_name": "Barrios",
            "profile": {
                "phone": "+34661661662",
                "picture": "",
                "type": "PRO",
                "iban_bank_account": "ES5221003179712200170953",
                "swift_bank_account": "CAGLESMMCOP",
                "documents": ["http://www.facebook.com/", "http://www.google.es"],
                "city": [598]
            },
            "new_zones": [1],
            "new_services": [1, 3, 0]
        }

        client = APIClient()
        response = client.patch('/api/1.0/user/', data=data, format='json',
                                HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data.get('new_services')[0], _("Invalid pk \"0\" - object does not exist."))
Пример #11
0
    def test_user_professional_ok(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)

        data = {
            "first_name": "Aurora",
            "last_name": "Barrios",
            "profile": {
                "phone": "+34661661662",
                "picture": "",
                "type": "PRO",
                "iban_bank_account": "ES5221003179712200170953",
                "swift_bank_account": "CAGLESMMCOP",
                "documents": ["http://www.facebook.com/", "http://www.google.es"],
                "work_days": [1, 2, 3, 4, 5],
                "work_hours": [11, 12, 13, 16, 17, 18, 19],
                "city": [598]
            },
            "new_zones": [1],
            "new_services": [1, 3]
        }

        client = APIClient()
        response = client.patch('/api/1.0/user/', data=data, format='json',
                                HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
def settings_data(request):
    result_data = ''

    if request.host.urlconf == 'home.urls_tower':
        if request.user.is_authenticated:
            all_count = Track.objects.filter(user=request.user,
                                             is_deleted=False).count()
            on_stage_count = Track.objects.filter(user=request.user,
                                                  is_deleted=False,
                                                  on_stage=1).count()
            open_mic_count = Track.objects.filter(user=request.user,
                                                  is_deleted=False,
                                                  on_stage=0).count()
        else:
            all_count = 0
            on_stage_count = 0
            open_mic_count = 0

        result_data = {
            'API_URL': settings.API_URL,
            'JWT_TOKEN': jwt_encode(request.user),
            'TRACK_COUNT': {
                'all': all_count,
                'on_stage': on_stage_count,
                'open_mic': open_mic_count
            }
        }

    return result_data
Пример #13
0
    def test_create_hire_service_ko_credit_card_card_not_exist(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)
        self.customer = FAKE_CUSTOMER.create_for_user(self.final)
        Card.sync_from_stripe_data(deepcopy(FAKE_CARD))

        data = {
            "client": self.final.pk,
            "professional": self.professional.pk,
            "date": "2028-10-10",
            "time": "18:00:00",
            "address": "Aligustre 20",
            "city": "Madrid",
            "region": "Madrid",
            "country": "Spain",
            "zip_code": "28039",
            "services": [self.service_1.pk, self.service_3.pk],
            "comments": "Hola",
            "total": 10.00,
            "credit_card": FAKE_CARD_II["id"]
        }

        client = APIClient()
        response = client.post(
            "/1.0/hire-services/",
            data=data,
            format='json',
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            response.data.get('credit_card')[0],
            _("Credit card id is not included in app."))
Пример #14
0
 def perform_create(self, serializer):
     user = serializer.save(self.request)
     if getattr(settings, "REST_USE_JWT", False):
         self.token = jwt_encode(user)
     email = EmailAddress.objects.get(user=user, email=user.email)
     confirmation = EmailConfirmationHMAC(email)
     tasks.send_confirmation_email.delay(user.username, user.email, confirmation.key)
     return user
Пример #15
0
    def perform_create(self, serializer):
        user = serializer.save(self.request)
        if getattr(settings, 'REST_USE_JWT', False):
            self.token = jwt_encode(user)
        else:
            create_token(self.token_model, user, serializer)

        return user
Пример #16
0
 def perform_create(self, serializer):
     user = serializer.save(self.request)
     if getattr(settings, 'REST_USE_JWT', False):
         self.token = jwt_encode(user)
     else:
         create_token(self.token_model, user, serializer)
     complete_signup(self.request._request, user,
                     allauth_settings.EMAIL_VERIFICATION, None)
     return user
Пример #17
0
 def perform_create(self, serializer):
     user = serializer.save(self.request)
     if getattr(settings, 'REST_USE_JWT', False):
         self.token = jwt_encode(user)
     email = EmailAddress.objects.get(user=user, email=user.email)
     confirmation = EmailConfirmationHMAC(email)
     print("key ->>>", confirmation.key)
     # TODO send email confirmation here
     return user
Пример #18
0
    def test_user_is_professional_invalid_date(self):
        professional = self.professional_2
        token_jwt_1 = jwt_encode(professional)

        client = APIClient()
        response = client.delete(
            "/1.0/days-off/11-11-2017/",
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Пример #19
0
    def test_user_is_professional(self):
        professional = self.professional
        token_jwt_1 = jwt_encode(professional)

        client = APIClient()
        response = client.get("/1.0/hire-services/", format='json', HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        self.assertEqual(len(data), 3)
Пример #20
0
    def test_user_is_professional(self):
        professional = self.professional
        token_jwt_1 = jwt_encode(professional)

        client = APIClient()
        response = client.delete(
            "/1.0/days-off/2017-12-03/",
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(self.days_off_total - 1, DayOff.objects.count())
Пример #21
0
    def perform_create(self, serializer):
        user = serializer.save(self.request)
        if getattr(settings, 'REST_USE_JWT', False):
            self.token = jwt_encode(user)

        email = EmailAddress.objects.get(email=user.email, user=user)
        email.verified = True
        email.primary = True
        email.save()
        return user
Пример #22
0
 def perform_create(self, serializer):
     user = serializer.save()
     if getattr(settings, 'REST_USE_JWT', False):
         self.token = jwt_encode(user)
     else:
         create_token(self.token_model, user, serializer)
     complete_signup(self.request._request, user,
                     allauth_settings.EMAIL_VERIFICATION,
                     None)
     return user
Пример #23
0
    def login(self):
        self.user = self.serializer.validated_data['user']

        if getattr(settings, 'REST_USE_JWT', False):
            self.token = jwt_encode(self.user)
        else:
            self.token = create_token(self.token_model, self.user,
                                      self.serializer)

        if getattr(settings, 'REST_SESSION_LOGIN', True):
            self.process_login()
Пример #24
0
    def test_user_is_final_filter_by_status(self):
        final = self.final
        token_jwt_1 = jwt_encode(final)

        client = APIClient()
        response = client.get("/1.0/hire-services/?status=PEN", format='json',
                              HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        self.assertEqual(len(data), 2)
    def test_cancel_hire_service_final_ok_status_pending(self):
        final = self.final
        token_jwt_1 = jwt_encode(final)

        client = APIClient()
        response = client.delete(
            "/1.0/hire-services/{0}/".format(self.hire_service_1.pk),
            data={},
            format='json',
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Пример #26
0
    def perform_create(self, serializer):
        user = serializer.save(self.request)
        if getattr(settings, "REST_USE_JWT", False):
            self.token = jwt_encode(user)

        email = EmailAddress.objects.get(email=user.email, user=user)
        confirmation = EmailConfirmationHMAC(email)
        key = confirmation.key
        # TODO Send mail confirmation here .
        # send_register_mail.delay(user, key)
        print("account-confirm-email/" + key)
        return user
Пример #27
0
    def test_user_is_professional_without_user_services(self):
        professional = self.professional
        token_jwt_1 = jwt_encode(professional)

        UserService.objects.filter(user=professional).delete()

        client = APIClient()
        response = client.get("/1.0/hire-services/", format='json', HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        self.assertEqual(len(data), 2)
    def test_cancel_hire_service_professional_ko_status_accept_date_passed(
            self):
        professional = self.professional
        token_jwt_1 = jwt_encode(professional)

        client = APIClient()
        response = client.delete(
            "/1.0/hire-services/{0}/".format(self.hire_service_2.pk),
            data={},
            format='json',
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Пример #29
0
    def test_accept_hire_service_professional__ok(self):
        professional = self.professional
        token_jwt_1 = jwt_encode(professional)

        data = {"accept": True, "id": self.hire_service_1.pk}

        client = APIClient()
        response = client.put(
            "/1.0/hire-services/",
            data=data,
            format='json',
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Пример #30
0
    def test_accept_hire_service_id_not_sent(self):
        professional = self.professional
        token_jwt_1 = jwt_encode(professional)

        data = {"accept": True}

        client = APIClient()
        response = client.put(
            "/1.0/hire-services/",
            data=data,
            format='json',
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Пример #31
0
    def test_superuser_is_login_error_services_not_sent(self):
        superuser = User.objects.get(username='******')
        token_jwt_1 = jwt_encode(superuser)

        data = {"zip": "28029", "date": "2017-12-06", "time": "18:09"}

        client = APIClient()
        response = client.post(
            "/1.0/professionals-availability/",
            data=data,
            format='json',
            HTTP_AUTHORIZATION='Token {}'.format(token_jwt_1))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Пример #32
0
def acs(r):
    saml_client = _get_saml_client(get_current_domain(r))
    resp = r.POST.get('SAMLResponse', None)
    next_url = r.session.get('login_next_url', _default_next_url())

    if not resp:
        return HttpResponseRedirect(get_reverse([denied, 'denied', 'django_saml2_auth:denied']))

    authn_response = saml_client.parse_authn_request_response(
        resp, entity.BINDING_HTTP_POST)
    if authn_response is None:
        return HttpResponseRedirect(get_reverse([denied, 'denied', 'django_saml2_auth:denied']))

    user_identity = authn_response.get_identity()
    if user_identity is None:
        return HttpResponseRedirect(get_reverse([denied, 'denied', 'django_saml2_auth:denied']))

    user_email = user_identity[settings.SAML2_AUTH.get('ATTRIBUTES_MAP', {}).get('email', 'Email')][0]
    user_name = user_identity[settings.SAML2_AUTH.get('ATTRIBUTES_MAP', {}).get('username', 'UserName')][0]
    user_first_name = user_identity[settings.SAML2_AUTH.get('ATTRIBUTES_MAP', {}).get('first_name', 'FirstName')][0]
    user_last_name = user_identity[settings.SAML2_AUTH.get('ATTRIBUTES_MAP', {}).get('last_name', 'LastName')][0]

    target_user = None
    is_new_user = False

    try:
        target_user = User.objects.get(username=user_name)
        if settings.SAML2_AUTH.get('TRIGGER', {}).get('BEFORE_LOGIN', None):
            import_string(settings.SAML2_AUTH['TRIGGER']['BEFORE_LOGIN'])(user_identity)
    except User.DoesNotExist:
        new_user_should_be_created = settings.SAML2_AUTH.get('CREATE_USER', True)
        if new_user_should_be_created: 
            target_user = _create_new_user(user_name, user_email, user_first_name, user_last_name)
            if settings.SAML2_AUTH.get('TRIGGER', {}).get('CREATE_USER', None):
                import_string(settings.SAML2_AUTH['TRIGGER']['CREATE_USER'])(user_identity)
            is_new_user = True
        else:
            return HttpResponseRedirect(get_reverse([denied, 'denied', 'django_saml2_auth:denied']))

    r.session.flush()

    if target_user.is_active:
        target_user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(r, target_user)
    else:
        return HttpResponseRedirect(get_reverse([denied, 'denied', 'django_saml2_auth:denied']))

    if settings.SAML2_AUTH.get('USE_JWT') is True:
        # We use JWT auth send token to frontend
        jwt_token = jwt_encode(target_user)
        query = '?uid={}&token={}'.format(target_user.id, jwt_token)

        frontend_url = settings.SAML2_AUTH.get(
            'FRONTEND_URL', next_url)

        return HttpResponseRedirect(frontend_url+query)

    if is_new_user:
        try:
            return render(r, 'django_saml2_auth/welcome.html', {'user': r.user})
        except TemplateDoesNotExist:
            return HttpResponseRedirect(next_url)
    else:
        return HttpResponseRedirect(next_url)