Example #1
0
def token_generate():
    queryset = MyUser.objects.all()
    Token.objects.filter(user__in=queryset).delete()
    new_tokens = [
        Token(user=u, key=Token.generate_key()) for u in queryset.iterator()
    ]
    Token.objects.bulk_create(new_tokens)
Example #2
0
    def post(self, request, *args, **kwargs):
        """
        Handle POST requests: instantiate a form instance with the passed
        POST variables and then check if it's valid.
        """
        form = self.get_form()
        if form.is_valid():
            username = request.POST['username']
            try:
                user = User.objects.get(username=username)
            except:
                user = None
            if user:
                password = form.cleaned_data.get("password")
                user_login = authenticate(username=username, password=password)
                request.session['user'] = user.username
                if user_login:
                    user_token = Token(user=user)
                    user_token.save()
                else:
                    return self.form_invalid(form)

            return self.form_valid(form)

        else:
            return self.form_invalid(form)
 def handle(self, *args, **options):
     try:
         email = options['email']
         EmailValidator()(email)
     except ValidationError as exc:
         raise CommandError(exc)
     with transaction.atomic():
         try:
             user = User.objects.create_user(
                 options['username'],
                 email,
                 options['password'],
                 is_staff=True
             )
             user.save()
         except IntegrityError as exc:
             raise CommandError(exc)
         token = options.get('token')
         if token:
             t = Token(user_id=user.id, key=token)
         else:
             t = Token(user_id=user.id)
         t.save()
         msg = (
             'successfully create user(username="******", email="{}")'
             ' with token "{}".'
         ).format(options['username'], email, t.key)
         self.stdout.write(self.style.SUCCESS(msg))
Example #4
0
    def post(self, request, format=None):
        try:
            data = request.data
        except ParseError as error:
            return Response('Invalid JSON - {0}'.format(error.detail),
                            status=status.HTTP_400_BAD_REQUEST)
        response = {}
        u = User(username=data['mobile'])
        u.set_password(data['password'])
        u.save()
        response['U_ID'] = u.id

        d = Doctor.objects.get(id=data['doctor'])

        p = Patient(name=data['name'],
                    mobile=data['mobile'],
                    email=data['email'],
                    address=data['address'],
                    date_of_birth=data['date_of_birth'],
                    gender=data['gender'],
                    user=u,
                    doctor=d)
        p.save()
        response['ID'] = p.id
        t = Token(user=u)
        t.save()
        response['Token'] = t.key

        return JsonResponse(response,
                            safe=False,
                            content_type='application/json')
Example #5
0
def getToken(user_id):

    if user_id:
        # first check previous token if exist then delete
        # we will look option update_or_create
        try:
            token = Token.objects.get(user_id=user_id)
            token.delete()
        except Token.DoesNotExist:
            # No need to log exception here :
            pass
        token = Token()
        token.user_id = user_id
        token.created = datetime.datetime.utcnow().replace(tzinfo=utc)
        try:
            token.save()
            return token.key
        except Exception as e:
            logger.critical(
                "Unhandled exception in {}, {}".format(
                    __name__, e))
            ravenclient.captureException()
            return None
        # End
    else:
        return None
Example #6
0
def forgot_password(request):
    serial = ForgotPassword(data=request.data)
    if serial.is_valid():
        email = serial.validated_data['email']
        try:
            user = User.objects.get(email=email)
        except:
            user = None
        if user is not None:
            token = Token(key=secrets.token_urlsafe(10), user_id=user.id)
            token.save()
        else:
            raise serializers.ValidationError(
                {'email': 'user with the email address not exist '})

        subject = 'Tribalmart Mail'
        message = 'Please click the below link to reset your password \nhttp://localhost:8000/account/reset/' + str(
            token)
        from_email = settings.EMAIL_HOST_USER
        tolist = [email]
        send_mail(subject, message, from_email, tolist)
        data = {'reset': 'reset password'}
    else:
        data = serial.errors
    return Response(data)
    def logout(self, request):
        try:
            Token.delete(request.user.auth_token)
        except Exception:
            pass

        return Response(status=status.HTTP_200_OK)
 def setUp(self):
     self.users = UserFactory.create_batch(size=2)
     self.factory = APIRequestFactory()
     self.client = APIClient()
     token = Token(user=self.users[0])
     token.save()
     self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
Example #9
0
 def test_get_pointer_data_with_pk(self):
     point = self.create_pointer_with_user(self.user2, 'party1')
     token = Token(user=self.user2)
     token.save()
     request = self.client.get('/point/pointer_data/' + str(point.id) + '/',
                               HTTP_AUTHORIZATION="Token {}".format(token))
     self.assertEqual(request.status_code, 200)
Example #10
0
    def post(self, request, format=None):
        try:
            data = request.data
        except ParseError as error:
            return Response('Invalid JSON - {0}'.format(error.detail),
                            status=status.HTTP_400_BAD_REQUEST)
        response = {}
        u = User(username=data['mobile'])
        u.set_password(data['password'])
        u.save()
        response['U_ID'] = u.id

        d = Doctor(
            name=data['name'],
            mobile=data['mobile'],
            email=data['email'],
            hospital=data['hospital'],
            # fcm=data['fcm'],
            user=u)
        d.save()
        response['ID'] = d.id

        t = Token(user=u)
        t.save()
        response['Token'] = t.key

        return JsonResponse(response,
                            safe=False,
                            content_type='application/json')
Example #11
0
    def test_user_pointer_story(self):
        self.client.logout()
        user2 = User.objects.create_user(username="******", \
            password="******", email="email2")
        user3 = User.objects.create_user(username="******", \
            password="******", email="email3")
        user4 = User.objects.create_user(username="******", \
            password="******", email="email4")
        self.create_pointer_with_user(user2, 'party1')
        self.create_pointer_with_user(user3, 'party2')
        self.create_pointer_with_user(user4, 'party3')
        self.create_pointer_with_user(user2, 'party123')

        fr1 = Friendship.objects.create_friendship(self.user1, user2)
        Friendship.objects.create_friendship(self.user1, user3)
        Friendship.objects.create_friendship(self.user1, user4)
        # not friends with self.user5

        token = Token(user=self.user1)
        token.save()
        request = self.client.get('/point/user_story_list/',
                                  HTTP_AUTHORIZATION="Token {}".format(token))
        self.assertEqual(len(request.data), 4)

        # if self.user1 not friends with user2 then only 2 pointer in story
        fr1.delete()
        request = self.client.get('/point/user_story_list/',
                                  HTTP_AUTHORIZATION="Token {}".format(token))
        self.assertEqual(len(request.data), 2)
Example #12
0
	def create(self, request, *args, **kwargs):
		LOGGER.debug("Received request for creating user")
		with transaction.atomic():
			serializer = self.get_serializer_class()(data=request.data)
			serializer.is_valid(raise_exception=True)
			user_instance = serializer.save()
			
			password = request.data["password"]
			user_instance.set_password(password)
			user_instance.is_active = False
			user_instance.save()
		
			#create token for newly created user
			LOGGER.debug("creating token for user")
			
			user_token = Token(user=user_instance)
			user_token.save()
			
			LOGGER.debug("Created token for user")
		
			target_url = request.build_absolute_uri(reverse("signup-activate"))
			send_account_activation_email.delay(user_instance.id, target_url, task_id=uuid.uuid4())
			
			LOGGER.debug("Added task for sending request to user asynchronously")
		
		user_dtls_serializer = UserPrimaryDtlsSerializer(instance=user_instance)
		LOGGER.info("User: %s created successfully", user_instance.username)
		
		return Response(user_dtls_serializer.data, status=HTTP_201_CREATED)
 def test_two_different_demo_users_when_no_cookie(self):
     response = self.client.put(self.url)
     demo_token = Token(response.data['token'])
     client2 = APIClient()
     response2 = client2.put(self.url)
     demo_token2 = Token(response2.data['token'])
     self.assertNotEqual(demo_token, demo_token2)
Example #14
0
def twitter(request):
    request_token_url = 'https://api.twitter.com/oauth/request_token'
    access_token_url = 'https://api.twitter.com/oauth/access_token'
    authenticate_url = 'https://api.twitter.com/oauth/authenticate'

    consumer_key = settings.SOSH["twitter"]["CONSUMER_KEY"]
    consumer_secret = settings.SOSH["twitter"]["CONSUMER_SECRET"]
    callback = settings.SOSH["twitter"]["CALLBACK_URL"]

    if request.GET.get('oauth_token') and request.GET.get('oauth_verifier'):
        auth = OAuth1(
            consumer_key,
            consumer_secret,
            request.GET.get("oauth_token"),
            verifier=request.GET.get("oauth_verifier"))
        r = requests.post(access_token_url, auth=auth)
        profile = dict(parse_qsl(r.text))

        provider = "twitter"
        uid = profile["user_id"]
        display_name = profile["screen_name"]
        username = "******" % (provider, uid)

        try:
            social_user = SocialUser.objects.get(uid=uid, provider="twitter")
            social_user.access_token = "Twitter"
            social_user.extra_data = profile
            social_user.save()
            token = Token.objects.get(user=social_user.user)
        except SocialUser.DoesNotExist:
            user, created = get_user_model() \
                .objects.get_or_create(username=username,
                                       display_name=display_name)
            if created:
                token = Token(user=user)
                token.save()
            else:
                token = Token.objects.get(user=user)

            social_user, created = SocialUser \
                .objects.get_or_create(
                    provider="twitter", user=user, uid=uid)
            if created:
                social_user.display_name = display_name
                social_user.access_token = "Twitter"
                social_user.extra_data = profile
                social_user.save()
        output = {}
        output["key"] = token.key
        return HttpResponse(json.dumps(output))
    else:
        oauth = OAuth1(
            consumer_key,
            client_secret=consumer_secret,
            callback_uri=callback)
        r = requests.post(request_token_url, auth=oauth)
        oauth_token = dict(parse_qsl(r.text))
        qs = urlencode(dict(oauth_token=oauth_token['oauth_token']))
        return redirect("%s?%s" % (authenticate_url, qs))
Example #15
0
def google(request):
    data = json.loads(request.body)
    access_token_url = 'https://accounts.google.com/o/oauth2/token'
    people_api_url = \
        'https://www.googleapis.com/plus/v1/people/me/openIdConnect'
    payload = dict(
        client_id=data["clientId"],
        redirect_uri=data['redirectUri'],
        client_secret=settings.SOSH["google"]["CLIENT_SECRET"],
        code=data['code'],
        grant_type="authorization_code"
    )
    r = requests.post(access_token_url, data=payload)
    token = json.loads(r.text)
    access_token = token["access_token"]
    headers = {'Authorization': 'Bearer %s' % (access_token)}

    r = requests.get(people_api_url, headers=headers)
    profile = json.loads(r.text)

    provider = "google"
    uid = profile["sub"]
    display_name = profile["name"]
    username = "******" % (provider, uid)

    email = None
    if "email" in profile:
        email = profile["email"]

    try:
        social_user = SocialUser.objects.get(uid=uid, provider="google")
        social_user.access_token = access_token
        social_user.extra_data = profile
        social_user.save()
        token = Token.objects.get(user=social_user.user)
    except SocialUser.DoesNotExist:
        user, created = get_user_model() \
            .objects.get_or_create(
                username=username,
                display_name=display_name,
                avatar=profile["picture"],
                email=email)
        if created:
            token = Token(user=user)
            token.save()
        else:
            token = Token.objects.get(user=user)

        social_user, created = SocialUser \
            .objects.get_or_create(provider="google", user=user, uid=uid)
        if created:
            social_user.display_name = display_name
            social_user.access_token = access_token
            social_user.extra_data = profile
            social_user.save()

    output = {}
    output["key"] = token.key
    return HttpResponse(json.dumps(output))
Example #16
0
 def setUpClass(cls):
     user = User.objects.create_user(username="******", password="******")
     t = Token(user=user)
     t.save()
     user_token = t.key
     cls.client = APIClient()
     #cls.client.login(username="******", password="******")
     cls.client.credentials(HTTP_AUTHORIZATION='Token ' + user_token)
Example #17
0
    def post(self, request):
        user_data = request.data

        if 'token' in user_data:
            Token.delete(user_data.get('token'))
            return Response({"message": "signed out"}, status.HTTP_200_OK)
        else:
            raise ValidationError('No token provided')
Example #18
0
 def get(self, request):
     try:
         token = Token.objects.get(user=request.user)
         # expire the token.
         Token.delete(token)
         return Response({'Message': 'Logout succeed.'}, status=200)
     except:
         return Response({'error': 'Logout error.'}, status=400)
Example #19
0
    def test_pointer_data_serializer_with_members(self):
        Friendship.objects.create_friendship(self.user1, self.user2)
        point = self.create_pointer_with_user(self.user1, 'party123')

        token = Token(user=self.user1)
        token.save()
        request = self.client.get('/point/pointer_data/' + str(point.id) + '/',
                                  HTTP_AUTHORIZATION="Token {}".format(token))
        self.assertEqual(len(request.data["members"]), 0)
Example #20
0
class RequestViewTest(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user(username="******",
                                              password="******",
                                              email="*****@*****.**")
        self.user1.is_active = True
        self.user1.save()
        self.user2 = User.objects.create_user(username="******", email="email2")
        self.user3 = User.objects.create_user(username="******", email="email3")
        self.user4 = User.objects.create_user(username="******", email="email4")
        self.client.login(username=self.user1.username, \
            password='******')

        self.token = Token(user=self.user1)
        self.token.save()

    def tearDown(self):
        self.client.logout()

    def createRequests(self):
        Request.objects.send_request(from_user=self.user2, to_user=self.user1)
        Request.objects.send_request(from_user=self.user2, to_user=self.user3)
        Request.objects.send_request(from_user=self.user1, to_user=self.user4)

    def createFriendships(self):
        Friendship.objects.create_friendship(from_user=self.user2,
                                             to_user=self.user1)
        Friendship.objects.create_friendship(from_user=self.user2,
                                             to_user=self.user3)
        Friendship.objects.create_friendship(from_user=self.user1,
                                             to_user=self.user4)

    def test_list_of_friends_is_displayed(self):
        self.createFriendships()
        friendslist = self.client.get("/friends/friends_list/",
                                      HTTP_AUTHORIZATION="Token {}".format(
                                          self.token))
        self.assertEqual(friendslist.status_code, 200)
        self.assertEqual(len(friendslist.data),
                         len(Friendship.objects.friends_list(self.user1)))

    def test_remove_friendship(self):
        friendship = Friendship.objects.create_friendship(from_user=self.user1,
                                                          to_user=self.user2)
        response = self.client.post("/friends/remove_friendship/" +
                                    str(self.user2.pk) + '/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(Friendship.objects.all().count(), 0)

    def test_remove_friendship_with_unfriended(self):
        friendship = Friendship.objects.create_friendship(from_user=self.user1,
                                                          to_user=self.user2)
        response = self.client.post("/friends/remove_friendship/" +
                                    str(self.user3.pk) + '/')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertFalse(Friendship.objects.are_friends(
            self.user1, self.user3))
Example #21
0
def twitter(request):
    request_token_url = 'https://api.twitter.com/oauth/request_token'
    access_token_url = 'https://api.twitter.com/oauth/access_token'
    authenticate_url = 'https://api.twitter.com/oauth/authenticate'

    consumer_key = settings.SOSH["twitter"]["CONSUMER_KEY"]
    consumer_secret = settings.SOSH["twitter"]["CONSUMER_SECRET"]
    callback = settings.SOSH["twitter"]["CALLBACK_URL"]

    if request.GET.get('oauth_token') and request.GET.get('oauth_verifier'):
        auth = OAuth1(consumer_key,
                      consumer_secret,
                      request.GET.get("oauth_token"),
                      verifier=request.GET.get("oauth_verifier"))
        r = requests.post(access_token_url, auth=auth)
        profile = dict(parse_qsl(r.text))

        provider = "twitter"
        uid = profile["user_id"]
        display_name = profile["screen_name"]
        username = "******" % (provider, uid)

        try:
            social_user = SocialUser.objects.get(uid=uid, provider="twitter")
            social_user.access_token = "Twitter"
            social_user.extra_data = profile
            social_user.save()
            token = Token.objects.get(user=social_user.user)
        except SocialUser.DoesNotExist:
            user, created = get_user_model() \
                .objects.get_or_create(username=username,
                                       display_name=display_name)
            if created:
                token = Token(user=user)
                token.save()
            else:
                token = Token.objects.get(user=user)

            social_user, created = SocialUser \
                .objects.get_or_create(
                    provider="twitter", user=user, uid=uid)
            if created:
                social_user.display_name = display_name
                social_user.access_token = "Twitter"
                social_user.extra_data = profile
                social_user.save()
        output = {}
        output["key"] = token.key
        return HttpResponse(json.dumps(output))
    else:
        oauth = OAuth1(consumer_key,
                       client_secret=consumer_secret,
                       callback_uri=callback)
        r = requests.post(request_token_url, auth=oauth)
        oauth_token = dict(parse_qsl(r.text))
        qs = urlencode(dict(oauth_token=oauth_token['oauth_token']))
        return redirect("%s?%s" % (authenticate_url, qs))
Example #22
0
def google(request):
    data = json.loads(request.body)
    access_token_url = 'https://accounts.google.com/o/oauth2/token'
    people_api_url = \
        'https://www.googleapis.com/plus/v1/people/me/openIdConnect'
    payload = dict(client_id=data["clientId"],
                   redirect_uri=data['redirectUri'],
                   client_secret=settings.SOSH["google"]["CLIENT_SECRET"],
                   code=data['code'],
                   grant_type="authorization_code")
    r = requests.post(access_token_url, data=payload)
    token = json.loads(r.text)
    access_token = token["access_token"]
    headers = {'Authorization': 'Bearer %s' % (access_token)}

    r = requests.get(people_api_url, headers=headers)
    profile = json.loads(r.text)

    provider = "google"
    uid = profile["sub"]
    display_name = profile["name"]
    username = "******" % (provider, uid)

    email = None
    if "email" in profile:
        email = profile["email"]

    try:
        social_user = SocialUser.objects.get(uid=uid, provider="google")
        social_user.access_token = access_token
        social_user.extra_data = profile
        social_user.save()
        token = Token.objects.get(user=social_user.user)
    except SocialUser.DoesNotExist:
        user, created = get_user_model() \
            .objects.get_or_create(
                username=username,
                display_name=display_name,
                avatar=profile["picture"],
                email=email)
        if created:
            token = Token(user=user)
            token.save()
        else:
            token = Token.objects.get(user=user)

        social_user, created = SocialUser \
            .objects.get_or_create(provider="google", user=user, uid=uid)
        if created:
            social_user.display_name = display_name
            social_user.access_token = access_token
            social_user.extra_data = profile
            social_user.save()

    output = {}
    output["key"] = token.key
    return HttpResponse(json.dumps(output))
Example #23
0
    def test_with_point_list(self):
        self.client.logout()
        self.create_pointer(title="party1")
        self.create_pointer(title="party2")
        token = Token(user=self.user1)
        token.save()
        request = self.client.get('/point/author_pointer_list/',
                                  HTTP_AUTHORIZATION="Token {}".format(token))

        self.assertEqual(len(request.data), 2)
Example #24
0
        def assert_token_is_deleted(token: Token, user: User,
                                    client: APIClient):
            self.assertTrue(hasattr(user, "auth_token"))
            self.assertEqual(
                client.post(logout_path).status_code, status.HTTP_200_OK)

            user.refresh_from_db()
            self.assertFalse(hasattr(user, "auth_token"))
            with self.assertRaises(Token.DoesNotExist):
                token.refresh_from_db()
    def _authenicate(self, user, json):
        try:
            token = Token.objects.get(user=user)
            Token.delete(token)
        except Token.DoesNotExist:
            pass

        token = Token.objects.create(user=user)
        json['token'] = token.key
        return json
Example #26
0
def create_token(application, token='', valid_days=1000, scope='read write'):
    expires = timezone.now() + timedelta(days=valid_days)

    if not token or not isinstance(token, basestring):
        token = Token.generate_key(Token(application.user.username))

    return AccessToken.objects.create(user=application.user,
                                      token=token,
                                      application=application,
                                      expires=expires,
                                      scope=scope)
Example #27
0
def facebook(request):
    data = json.loads(request.body)
    access_token_url = 'https://graph.facebook.com/oauth/access_token'
    graph_api_url = 'https://graph.facebook.com/me'
    params = {
        "client_id": "%s" % (data["clientId"]),
        "redirect_uri": "%s" % (data["redirectUri"]),
        "client_secret": settings.SOSH["facebook"]["CLIENT_SECRET"],
        "code": "%s" % (data["code"]),
    }

    r = requests.get(access_token_url, params=params)
    access_token = dict(parse_qsl(r.text))

    r = requests.get(graph_api_url, params=access_token)
    profile = json.loads(r.text)
    provider = "facebook"
    uid = profile["id"]
    display_name = profile["username"]
    username = "******" % (provider, uid)

    email = None
    if "email" in profile:
        email = profile["email"]

    try:
        social_user = SocialUser.objects.get(uid=uid, provider="facebook")
        social_user.access_token = access_token
        social_user.extra_data = profile
        social_user.save()
        token = Token.objects.get(user=social_user.user)
    except SocialUser.DoesNotExist:
        user, created = get_user_model() \
            .objects.get_or_create(
                username=username,
                display_name=display_name,
                email=email)
        if created:
            token = Token(user=user)
            token.save()
        else:
            token = Token.objects.get(user=user)

        social_user, created = SocialUser \
            .objects.get_or_create(provider="facebook", user=user, uid=uid)
        if created:
            social_user.display_name = display_name
            social_user.access_token = access_token
            social_user.extra_data = profile
            social_user.save()

    output = {}
    output["key"] = token.key
    return HttpResponse(json.dumps(output))
Example #28
0
 def get_token(self):
     # token = Token(user=self)
     # token.save()
     if hasattr(self, 'auth_token'):
         result_token = self.auth_token.key
     else:
         token = Token(user=self)
         token.save()
         result_token = token.key
     # result_token = 'test'
     return result_token
Example #29
0
    def create(self, validated_data):
        username = validated_data["username"]
        email = validated_data["email"]

        pollster = Pollster(username=username, email=email)
        pollster.set_password(validated_data["password"])
        pollster.save()
        token = Token(user=pollster)
        token.save()

        return pollster
Example #30
0
def facebook(request):
    data = json.loads(request.body)
    access_token_url = 'https://graph.facebook.com/oauth/access_token'
    graph_api_url = 'https://graph.facebook.com/me'
    params = {
        "client_id": "%s" % (data["clientId"]),
        "redirect_uri": "%s" % (data["redirectUri"]),
        "client_secret": settings.SOSH["facebook"]["CLIENT_SECRET"],
        "code": "%s" % (data["code"]),
    }

    r = requests.get(access_token_url, params=params)
    access_token = dict(parse_qsl(r.text))

    r = requests.get(graph_api_url, params=access_token)
    profile = json.loads(r.text)
    provider = "facebook"
    uid = profile["id"]
    display_name = profile["username"]
    username = "******" % (provider, uid)

    email = None
    if "email" in profile:
        email = profile["email"]

    try:
        social_user = SocialUser.objects.get(uid=uid, provider="facebook")
        social_user.access_token = access_token
        social_user.extra_data = profile
        social_user.save()
        token = Token.objects.get(user=social_user.user)
    except SocialUser.DoesNotExist:
        user, created = get_user_model() \
            .objects.get_or_create(
                username=username,
                display_name=display_name,
                email=email)
        if created:
            token = Token(user=user)
            token.save()
        else:
            token = Token.objects.get(user=user)

        social_user, created = SocialUser \
            .objects.get_or_create(provider="facebook", user=user, uid=uid)
        if created:
            social_user.display_name = display_name
            social_user.access_token = access_token
            social_user.extra_data = profile
            social_user.save()

    output = {}
    output["key"] = token.key
    return HttpResponse(json.dumps(output))
Example #31
0
 def setUpClass(cls):
     c = Country(name="INDIA", shortname="ind", description="eerew")
     c.save()
     user = UserProfile.objects.create_user(username="******",
                                            password="******",
                                            country=c)
     t = Token(user=user)
     t.save()
     token = t.key
     cls.token = token
     cls.client = APIClient()
Example #32
0
    def post(self, request):
        user = request.user
        token, created = Token.objects.get_or_create(user=user)
        if not created:
            token.delete()
            token = Token(user=user)
            token.save()

        return Response({
            'token': str(token),
            'user': UserSerializer(user).data,
        })
Example #33
0
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        
        token = Token()
        token.key, token.created  = None, None
                
        token, created = Token.objects.get_or_create(user=user)

        return Response({'token': token.key, 'id' : user.id, 'name' : user.first_name + " " + user.last_name })
Example #34
0
    def authentication(self):
        self.token = Token()

        self.token.user = User.objects.create(
            username=f'User{UUIDGenerator().generate()}',
            first_name=f'Пользователь {UUIDGenerator().generate()}',
            password=make_password('1234'),
            is_superuser=False,
            is_active=True)
        self.token.save()
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
        self.assertTrue(User.objects.all().exists())
Example #35
0
    def test_joke_creation_via_api(self):
        try:
            token = Token.objects.get(user=self.user1)
        except Exception:
            token = Token(user=self.user1)
            token.save()

        headers = {"Authorization": "Token %s" % (token.key)}
        data = {'user': self.user1, 'text': 'random joke'}
        client = APIClient()
        client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        response = client.post('/api/jokes/', data)
        self.assertEquals(response.status_code, 201)
Example #36
0
        def assert_token_is_replaced(user: User, user_password: str,
                                     old_token: Token, client: APIClient):
            old_token_key = old_token.key

            response = self._successfully_get_auth_token(
                user, user_password, client)
            new_token_key = response.data["token"]

            self.assertNotEqual(new_token_key, old_token_key)
            with self.assertRaises(Token.DoesNotExist):
                old_token.refresh_from_db()
            user.refresh_from_db()
            self.assertEqual(new_token_key, user.auth_token.key)
Example #37
0
 def get_object(self):
     user = self.request.user
     if user.is_authenticated():
         try:
             created = False
             token = user.auth_token.key
         except AuthToken.DoesNotExist:
             # Create one
             auth_token = AuthToken(user=user)
             auth_token.save()
             created = True
             token = auth_token.key
         return (dict(username=user.username,
                      password='', # for consistency
                      token=token),
                 created)
     else:
         return (dict(username="",
                      password="",
                      token=""),
                 False)
Example #38
0
    def setUp(self):
        self.client = APIClient()
        self.option = mommy.make('main.Option')
        self.items = mommy.make('main.Item', make_m2m=True, _quantity=50)
        self.item = mommy.make('main.Item', make_m2m=True)

        self.item_json = ItemSerializer(self.item).data
        self.status = mommy.make('main.Status')

        self.admin_user = mommy.make('main.ShopUser')
        self.admin_user.is_staff = True
        self.admin_user.save()
        self.reg_user = mommy.make('main.ShopUser')

        # Generate token for token auth based on the user in the requests
        self.admin_token = Token()
        self.admin_token.key = self.admin_token.generate_key()
        self.admin_token.user_id = self.admin_user.id
        self.admin_token.save()
        self.reg_token = Token()
        self.reg_token.key = self.reg_token.generate_key()
        self.reg_token.user_id = self.reg_user.id
        self.reg_token.save()
Example #39
0
    def setUp(self):
        self.crowd = Crowd(name='test_crowd')
        self.crowd.save()

        self.user = UserProfile(username='******', email='*****@*****.**',
                                password='******', crowd=self.crowd)
        self.user.save()

        # Include an appropriate `Authorization:` header on all requests.
        self.token = Token(user=self.user)
        self.token.save()

        self.category = Category(created_by=self.user,
                                 name='test_category',
                                 color='red', crowd=self.crowd)
        self.category.save()

        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
        self.viewset = PostViewSet.as_view({
            'get': 'retrieve',
            'put': 'update',
            'patch': 'partial_update',
            'delete': 'destroy'
        })
 def test_generate_key_returns_string(self):
     """Ensure generate_key returns a string"""
     token = Token()
     key = token.generate_key()
     self.assertTrue(isinstance(key, six.string_types))
Example #41
0
class PostTests(APITestCase):
    def setUp(self):
        self.crowd = Crowd(name='test_crowd')
        self.crowd.save()

        self.user = UserProfile(username='******', email='*****@*****.**',
                                password='******', crowd=self.crowd)
        self.user.save()

        # Include an appropriate `Authorization:` header on all requests.
        self.token = Token(user=self.user)
        self.token.save()

        self.category = Category(created_by=self.user,
                                 name='test_category',
                                 color='red', crowd=self.crowd)
        self.category.save()

        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
        self.viewset = PostViewSet.as_view({
            'get': 'retrieve',
            'put': 'update',
            'patch': 'partial_update',
            'delete': 'destroy'
        })

    def _get_response(self, urllib_mock, content_type):
        urllib_mock.headers.get.return_value = content_type
        return urllib_mock

    @mock.patch('website.models.Post._new_post_email')
    @mock.patch('urllib3.PoolManager')
    def test_create_text_post(self, urllib_mock, new_post_mock):
        urllib_mock = self._get_response(urllib_mock, 'text/html')
        url = reverse('post-list')
        data = {'category': self.category.id, 'title': 'test post'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual('text', response.data['type'])
        self.assertEqual(self.crowd.id, response.data['crowd']['id'])
        self.assertEqual(self.user.id, response.data['user']['id'])

        # Ensure we can get the post back
        get_response = self.client.get(
            '{}{}/'.format(url, response.data['id']))

        self.assertEqual(get_response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.crowd.id, get_response.data['crowd']['id'])
        self.assertEqual(self.user.id, get_response.data['user']['id'])

    @mock.patch('website.models.Post._new_post_email')
    @mock.patch('urllib3.PoolManager')
    def test_create_url_post(self, urllib_mock, new_post_mock):
        urllib_mock = self._get_response(urllib_mock, 'text/html')
        url = reverse('post-list')
        data = {'category': self.category.id, 'title': 'test post',
                'url': 'http://google.com/'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual('link', response.data['type'])
        self.assertEqual('http://google.com/', response.data['url'])
Example #42
0
class AdminDashboardViewsTestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.option = mommy.make('main.Option')
        self.items = mommy.make('main.Item', make_m2m=True, _quantity=50)
        self.item = mommy.make('main.Item', make_m2m=True)

        self.item_json = ItemSerializer(self.item).data
        self.status = mommy.make('main.Status')

        self.admin_user = mommy.make('main.ShopUser')
        self.admin_user.is_staff = True
        self.admin_user.save()
        self.reg_user = mommy.make('main.ShopUser')

        # Generate token for token auth based on the user in the requests
        self.admin_token = Token()
        self.admin_token.key = self.admin_token.generate_key()
        self.admin_token.user_id = self.admin_user.id
        self.admin_token.save()
        self.reg_token = Token()
        self.reg_token.key = self.reg_token.generate_key()
        self.reg_token.user_id = self.reg_user.id
        self.reg_token.save()

    def test_admin_create_item_view(self):
        Item.objects.get(id=self.item.id).delete()

        self.client.force_authenticate(self.admin_user, self.admin_token)
        request = self.client.post(reverse('create_item'), data=self.item_json, format='json')
        item = Item.objects.get(pk=52)

        self.assertEqual(request.status_code, 201)
        self.assertEqual(item.name, self.item_json['name'])
        self.assertEqual(item.description, self.item_json['description'])
        self.assertEqual(item.weight, decimal.Decimal(self.item_json['weight']))
        self.assertEqual(item.price, decimal.Decimal(self.item_json['price']))
        self.assertEqual(item.options.count(), len(self.item_json['options']))

    def test_admin_create_view_as_reg_user(self):
        Item.objects.get(id=self.item.id).delete()

        self.client.force_authenticate(self.reg_user, self.reg_token)
        request = self.client.post(reverse('create_item'), data=self.item_json, format='json')

        self.assertEqual(request.status_code, 403)
        with self.assertRaises(ObjectDoesNotExist):
            Item.objects.get(pk=52)

    def test_admin_item_list(self):
        self.client.force_authenticate(self.admin_user, self.admin_token)
        request = self.client.get(reverse('create_item'))
        data = json.loads(request.content)

        self.assertEqual(request.status_code, 200)
        self.assertEqual('count' in data, True)
        self.assertEqual('next' in data, True)
        self.assertEqual(len(data['results']), 25)

        for result in data['results']:
            self.assertEqual('id' in result, True)
            self.assertEqual('name' in result, True)
            self.assertEqual('description' in result, True)
            self.assertEqual('weight' in result, True)
            self.assertEqual('price' in result, True)
            self.assertEqual('options' in result, True)
            self.assertEqual('tags' in result, True)

    def test_admin_item_list_as_reg_user(self):
        self.client.force_authenticate(self.reg_user, self.reg_token)
        request = self.client.get(reverse('create_item'))
        self.assertEqual(request.status_code, 403)

    def test_admin_option_list(self):
        self.client.force_authenticate(self.admin_user, self.admin_token)
        request = self.client.get(reverse('create_option'))
        data = json.loads(request.content)

        self.assertEqual(request.status_code, 200)
        self.assertEqual(data['count'], 256)
        self.assertEqual(data['results'][0]['name'], self.option.name)

    def test_admin_option_list_as_reg_user(self):
        self.client.force_authenticate(self.reg_user, self.reg_token)
        request = self.client.get(reverse('create_option'))
        self.assertEqual(request.status_code, 403)

    def test_admin_option_detail(self):
        self.client.force_authenticate(self.admin_user, self.admin_token)
        request = self.client.get(reverse('option_detail_update', args=(1,)))
        data = json.loads(request.content)

        self.assertEqual(request.status_code, 200)
        self.assertEqual(data['id'], self.option.id)
        self.assertEqual(data['name'], self.option.name)

    def test_admin_option_detail_as_reg_user(self):
        self.client.force_authenticate(self.reg_user, self.reg_token)
        request = self.client.get(reverse('option_detail_update', args=(1,)))
        self.assertEqual(request.status_code, 403)

    def test_admin_status_list(self):
        self.client.force_authenticate(self.admin_user, self.admin_token)
        request = self.client.get(reverse('create_status'))
        data = json.loads(request.content)

        self.assertEqual(request.status_code, 200)
        self.assertEqual(data['count'], 1)
        self.assertEqual(data['results'][0]['status'], self.status.status)
        self.assertEqual(data['results'][0]['description'], self.status.description)

    def test_admin_status_list_as_reg_user(self):
        self.client.force_authenticate(self.reg_user, self.reg_token)
        request = self.client.get(reverse('create_status'))
        self.assertEqual(request.status_code, 403)

    def test_admin_status_detail(self):
        self.client.force_authenticate(self.admin_user, self.admin_token)
        request = self.client.get(reverse('status_detail_update', args=(1,)))
        data = json.loads(request.content)

        self.assertEqual(request.status_code, 200)
        self.assertEqual(data['status'], self.status.status)
        self.assertEqual(data['id'], self.status.id)
        self.assertEqual(data['description'], self.status.description)

    def test_admin_status_detail_as_reg_user(self):
        self.client.force_authenticate(self.reg_user, self.reg_token)
        request = self.client.get(reverse('status_detail_update', args=(1,)))
        self.assertEqual(request.status_code, 403)