def test_post_form_failing_jwt_auth_changed_user_secret_key(self):
        """
        Ensure changin secret key on USER level makes tokens invalid
        """
        # fine tune settings
        api_settings.JWT_GET_USER_SECRET_KEY = get_jwt_secret

        tmp_user = CustomUser.objects.create(email='*****@*****.**')
        payload = utils.jwt_payload_handler(tmp_user)
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        response = self.csrf_client.post(
            '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # change token, verify
        tmp_user.jwt_secret = uuid.uuid4()
        tmp_user.save()

        response = self.csrf_client.post(
            '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        # revert api settings
        api_settings.JWT_GET_USER_SECRET_KEY = DEFAULTS['JWT_GET_USER_SECRET_KEY']
Exemplo n.º 2
0
    def get_token(self, obj):
        #jwt_payload_handler = jwt_payload_handler
        #jwt_encode_handler = settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)
        return token
Exemplo n.º 3
0
    def post(self, request):
        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=request.data['clientId'],
                       redirect_uri=request.data['redirectUri'],
                       client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,
                       code=request.data['code'],
                       grant_type='authorization_code')

        # Step 1. Exchange authorization code for access token.
        r = requests.post(access_token_url, data=payload)
        token = json.loads(r.text)
        headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}

        # Step 2. Retrieve information about the current user.
        r = requests.get(people_api_url, headers=headers)
        profile = json.loads(r.text)

        user = None
        if 'email' in profile:
            try:
                user = User.objects.get(email=profile['email'])
            except User.DoesNotExist:
                pass

        if not user:
            user = User.objects.create(username=profile['email'], first_name=profile['given_name'],
                                       last_name=profile['family_name'], email=profile['email'])
            Better.objects.create(user=user)

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return Response({'token': token.decode('unicode_escape')},
                        status=status.HTTP_200_OK)
Exemplo n.º 4
0
    def test_jwt_encode(self):
        payload = utils.jwt_payload_handler(self.user)
        token = utils.jwt_encode_handler(payload)

        payload_data = base64url_decode(token.split('.')[1].encode('utf-8'))
        payload_from_token = json.loads(payload_data.decode('utf-8'))

        self.assertEqual(payload_from_token, payload)
Exemplo n.º 5
0
 def handle(self, *args, **options):
     try:
         user = CustomUser.objects.create_user(username=options["username"],
                                               password=options["password"])
         token = jwt_encode_handler(jwt_payload_handler(user))
         self.stdout.write(self.style.SUCCESS(str(token)))
     except IntegrityError as ex:
         raise CommandError(ex)
Exemplo n.º 6
0
    def _generate_jwt_token(self):
        """
        Generates a JSON Web Token that stores this user's ID and has an expiry
        date set to 60 days into the future.
        """
        payload = jwt_payload_handler(self)
        token = jwt_encode_handler(payload)

        return token
    def test_jwt_decode_verify_exp(self):
        api_settings.JWT_VERIFY_EXPIRATION = False

        payload = utils.jwt_payload_handler(self.user)
        payload['exp'] = 1
        token = utils.jwt_encode_handler(payload)
        utils.jwt_decode_handler(token)

        api_settings.JWT_VERIFY_EXPIRATION = True
Exemplo n.º 8
0
 def setUp(self):
     self.client = Client()
     self.username = '******'
     self.email = '*****@*****.**'
     self.user = User.objects.create_user(self.username, self.email)
     payload = utils.jwt_payload_handler(self.user)
     token = utils.jwt_encode_handler(payload)
     self.auth = 'Bearer {0}'.format(token)
     self.startTime = time.time()
Exemplo n.º 9
0
def a_superuser_with_a_jwtoken(context):

    user = User.objects.create_superuser(username='******',
                                         email='*****@*****.**',
                                         password='******')

    payload = utils.jwt_payload_handler(user)
    token = utils.jwt_encode_handler(payload)
    context.auth = 'JWT {0}'.format(token)
def test_authjwt_method(subscription, expect):
    if expect is True:
        payload = jwt_payload_handler(user=subscription.subscriber)
        token = jwt_encode_handler(payload)
    else:
        token = "fdksal;j"

    value = auth.authjwt_method(token)
    assert bool(value) is expect
Exemplo n.º 11
0
 def setUp(self):
     self.client = APIClient()
     self.username = '******'
     self.email = '*****@*****.**'
     self.password='******'
     self.user = User.objects.create_user(self.email, self.password, username=self.username)
     payload = utils.jwt_payload_handler(self.user)
     token = utils.jwt_encode_handler(payload)
     self.auth = 'Token {0}'.format(token)
Exemplo n.º 12
0
def test_authjwt_method(subscription, expect):
    if expect is True:
        payload = jwt_payload_handler(user=subscription.subscriber)
        token = jwt_encode_handler(payload)
    else:
        token = "fdksal;j"

    value = auth.authjwt_method(token)
    assert bool(value) is expect
Exemplo n.º 13
0
    def test_can_authenticate(self):
        payload = jwt_payload_handler(self.user)
        token = jwt_encode_handler(payload)

        response = self.client.get(reverse_lazy('offer:offer-list-api'), {},
                                   HTTP_AUTHORIZATION='JWT {}'.format(token))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, self.offer.title)
        self.assertContains(response, self.other_offer.title)
Exemplo n.º 14
0
    def validate(self, attrs):
        user = authenticate(**attrs)
        if user is None:
            raise serializers.ValidationError("用户名或密码错误!")

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return {'user': user, 'token': token}
Exemplo n.º 15
0
def createuserview(request):
    serializer = CreateUser(data=request.data)
    serializer.is_valid(raise_exception=True)
    username = request.data.get('username')
    password = request.data.get('password')
    user = User.objects.create_user(username=username, password=password)
    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    return Response(data={"token": token}, status=status.HTTP_201_CREATED)
Exemplo n.º 16
0
    def setUp(self):

        user = User.objects.create_superuser(username='******',
                                             email='*****@*****.**',
                                             password='******')

        payload = utils.jwt_payload_handler(user)
        token = utils.jwt_encode_handler(payload)

        self.auth = 'JWT {0}'.format(token)
 def test_get_refresth_token_detail(self):
     self.client.credentials(
         HTTP_AUTHORIZATION='JWT ' +
         utils.jwt_encode_handler(utils.jwt_payload_handler(self.user)))
     response = self.client.get(self.detail_url)
     self.assertEqual(response.status_code, status.HTTP_200_OK,
                      (response.status_code, response.content))
     response = self.client.get(self.detail_url1)
     self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND,
                      (response.status_code, response.content))
 def test_create_refresh_token(self):
     data = {'app': 'gandolf'}
     self.client.credentials(
         HTTP_AUTHORIZATION='JWT ' +
         utils.jwt_encode_handler(utils.jwt_payload_handler(self.user)))
     response = self.client.post(self.list_url, data, format='json')
     self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                      (response.status_code, response.content))
     self.assertEqual(response.data['user'], self.user.pk)
     self.assertEqual(response.data['app'], data['app'])
Exemplo n.º 19
0
    def create_token(self, user, exp=None, orig_iat=None):
        payload = utils.jwt_payload_handler(user)
        if exp:
            payload['exp'] = exp

        if orig_iat:
            payload['orig_iat'] = timegm(orig_iat.utctimetuple())

        token = utils.jwt_encode_handler(payload)
        return token
Exemplo n.º 20
0
    def create_token(self, user, exp=None, orig_iat=None):
        payload = utils.jwt_payload_handler(user)
        if exp:
            payload['exp'] = exp

        if orig_iat:
            payload['orig_iat'] = timegm(orig_iat.utctimetuple())

        token = utils.jwt_encode_handler(payload)
        return token
Exemplo n.º 21
0
def login(request):
    user = authenticate(username=request.data.get('username'),
                        password=request.data.get('password'))
    if not user:
        return Response(
            {"error": "Login failed. Incorrect username or password."},
            status=HTTP_401_UNAUTHORIZED)
    user.save()
    payload = jwt_payload_handler(user)
    jwt_token = jwt_encode_handler(payload)
    return Response({"token": jwt_token})
Exemplo n.º 22
0
 def setUp(self):
     self.client = APIClient()
     self.username = '******'
     self.email = '*****@*****.**'
     self.password = '******'
     self.user = User.objects.create_user(self.email,
                                          self.password,
                                          username=self.username)
     payload = utils.jwt_payload_handler(self.user)
     token = utils.jwt_encode_handler(payload)
     self.auth = 'Token {0}'.format(token)
Exemplo n.º 23
0
 def create(self, validated_data):
     user = User(
         username=validated_data['username'],
         email=validated_data['email'],
         first_name=validated_data['first_name'],
         last_name=validated_data['last_name'],
     )
     user.set_password(validated_data['password'])
     user.save()
     user.token = jwt_encode_handler(jwt_payload_handler(user))
     return user
Exemplo n.º 24
0
    def post(self, request, format=None):
        serializer = SMSCodeSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        mobile = serializer.validated_data['mobile']
        #生成随机验证码,向目标手机发送验证码,用手机号码和验证码生成token
        token = jwt_encode_handler({
            'exp': timezone.now() + settings.JWT_AUTH['SMS_TOKEN_EXP_DELTA'],  #有效期:3分钟
            'mobile': mobile,
            'sms_code': '118590'})
        return Response({'token': token}, status=status.HTTP_200_OK)
Exemplo n.º 25
0
    def test_verify_jwt(self) -> None:
        token = jwt_encode_handler(jwt_payload_handler(self.user))

        response = self.client.post(
            reverse('verify-token'),
            json.dumps({'token': token}),
            **DEFAULT_REQUEST_PARAMS,
            # Authorization=f'Bearer {token}'
        )

        self.assertIn('token', response.data)
Exemplo n.º 26
0
 def post(self, request, *args, **kwargs):
     form = self.get_form()
     if form.is_valid():
         user = form.get_user()
         payload = jwt_payload_handler(user)
         token = 'Bearer ' + jwt_encode_handler(payload)
         response = self.form_valid(form)
         response['Authorization'] = token
         return response
     else:
         return self.form_invalid(form)
Exemplo n.º 27
0
 def make_token(self, status):
     payload = {
         'user_id': self.user.id,
         'time_create': self.token,
     }
     token = jwt_encode_handler(payload)
     response_data = {
         'token': token
     }
     general_response = rsp.Response(response_data).generate_response()
     response = Response(general_response, status=status)
     return response
Exemplo n.º 28
0
    def test_post_with_expired_token_gets_error(self):
        # We're going to get a fresh token, sneakily set the expiration to 1, and then try to refresh with it.
        response = self.client.post('/jwt-auth/', self.data, format='json')
        decoded_payload = utils.jwt_decode_handler(response.data['token'])
        decoded_payload['exp'] = 1
        token = utils.jwt_encode_handler(decoded_payload)
        response = self.client.post('/jwt-verify/', {'token': token},
                                    format='json')

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data['non_field_errors'][0],
                         'Signature has expired.')
Exemplo n.º 29
0
 def changeform_view(self,
                     request,
                     object_id=None,
                     form_url='',
                     extra_context=None):
     extra_context = extra_context or {}
     extra_context['token'] = jwt_encode_handler(
         jwt_payload_handler(request.user))
     return super().changeform_view(request,
                                    object_id=object_id,
                                    form_url=form_url,
                                    extra_context=extra_context)
Exemplo n.º 30
0
 def post(self, request, format=None):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         payload = jwt_payload_handler(user)
         token = jwt_encode_handler(payload)
         return Response({
             "user": serializer.data,
             "token": token
         },
                         status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 31
0
 def test_validate_service_jwt_fails_with_invalid_data(self):
     with self.assertRaises(ValidationError):
         payload = create_service_jwt_payload()
         payload.pop('exp')
         jwt = jwt_encode_handler(payload)
         validate_service_jwt(jwt)
     with self.assertRaises(ValidationError):
         payload = create_service_jwt_payload()
         payload.pop('service_name')
         jwt = jwt_encode_handler(payload)
         validate_service_jwt(jwt)
     with self.assertRaises(ValidationError):
         payload = create_service_jwt_payload()
         payload.pop('service_permissions')
         jwt = jwt_encode_handler(payload)
         validate_service_jwt(jwt)
     with self.assertRaises(ValidationError):
         payload = create_service_jwt_payload()
         payload.pop('is_service')
         jwt = jwt_encode_handler(payload)
         validate_service_jwt(jwt)
Exemplo n.º 32
0
    def validate(self, data):
        try:
            user = CtrlfUser.objects.get(email=data["email"])
        except CtrlfUser.DoesNotExist:
            raise serializers.ValidationError("이메일이 존재하지 않습니다.")

        if not check_password(data["password"], user.password):
            raise serializers.ValidationError("패스워드가 일치하지 않습니다.")

        payload = jwt_payload_handler(user)

        return {"token": jwt_encode_handler(payload), "user": user}
Exemplo n.º 33
0
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        user = authenticate(username=username, password=password)
        if not user or not user.is_active:
            raise serializers.ValidationError('传统验证失败')

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return {'user': user, 'token': token}
Exemplo n.º 34
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["user"] = user
        headers = self.get_success_headers(serializer.data)

        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
    def test_post_json_passing_jwt_auth(self):
        """
        Ensure POSTing JSON over JWT auth with correct credentials
        passes and does not require CSRF
        """
        payload = utils.jwt_payload_handler(self.user)
        token = utils.jwt_encode_handler(payload)

        auth = "JWT {0}".format(token)
        response = self.csrf_client.post("/jwt/", {"example": "example"}, HTTP_AUTHORIZATION=auth, format="json")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemplo n.º 36
0
 def post(self, request):
     from lazysignup.models import LazyUser
     user, username = LazyUser.objects.create_lazy_user()
     user.first_name = 'Guest' + str(random.randint(1, 200))
     user.save()
     betting_funds = random.randint(10, 60)
     Better.objects.create(user=user, points=betting_funds)
     payload = jwt_payload_handler(user)
     token = jwt_encode_handler(payload)
     return Response({'token': token, 'name': user.first_name,
                      'betting_funds': betting_funds },
                     status=status.HTTP_200_OK)
Exemplo n.º 37
0
    def get(self, request):
        try:
            if request.user.is_active:
                payload = jwt_payload_handler(request.user)  # todo: Is deprecated
                jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload),
                                                                   user=request.user)
                return responses.SuccessResponse(jwt_token).send()
            else:
                raise authnz_exceptions.CustomException(detail=_('This user is inactive, contact us.'))

        except authnz_exceptions.CustomException as e:
            return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
Exemplo n.º 38
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = self.perform_create(serializer)
     re_dict = serializer.data
     payload = jwt_payload_handler(user)
     re_dict['token'] = jwt_encode_handler(payload)
     re_dict['username'] = user.username
     headers = self.get_success_headers(serializer.data)
     return Response(re_dict,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Exemplo n.º 39
0
    def validate(self, attrs):
        username = attrs['username']
        password = attrs['password']

        user = authenticate(**attrs)
        if not user:
            raise serializers.ValidationError('shibai')
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return {
            'user': user,
            'token': 'token'
        }
Exemplo n.º 40
0
    def test_post_form_passing_jwt_auth(self):
        """
        Ensure POSTing json over JWT auth with correct credentials
        passes and does not require CSRF
        """
        payload = utils.jwt_payload_handler(self.user)
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        response = self.csrf_client.post(
            '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
    def test_post_passing_jwt_auth_with_oauth2_priority(self):
        """
        Ensure POSTing over JWT auth with correct credentials
        passes and does not require CSRF when OAuth2Authentication
        has priority on authentication_classes
        """
        payload = utils.jwt_payload_handler(self.user)
        token = utils.jwt_encode_handler(payload)

        auth = "JWT {0}".format(token)
        response = self.csrf_client.post("/oauth2-jwt/", {"example": "example"}, HTTP_AUTHORIZATION=auth, format="json")

        self.assertEqual(response.status_code, status.HTTP_200_OK, response)
    def test_post_form_passing_jwt_invalid_payload(self):
        """
        Ensure POSTing json over JWT auth with invalid payload fails
        """
        payload = dict(email=None)
        token = utils.jwt_encode_handler(payload)

        auth = "JWT {0}".format(token)
        response = self.csrf_client.post("/jwt/", {"example": "example"}, HTTP_AUTHORIZATION=auth)

        msg = "Invalid payload."

        self.assertEqual(response.data["detail"], msg)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
    def test_post_form_passing_jwt_invalid_payload(self):
        """
        Ensure POSTing json over JWT auth with invalid payload fails
        """
        payload = dict(user_id=1, email=None)
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        response = self.csrf_client.post(
            '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)

        msg = 'Invalid payload'

        self.assertEqual(response.data['detail'], msg)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
Exemplo n.º 44
0
    def test_jwt_login_with_expired_token(self):
        """
        Ensure JWT login view works even if expired token is provided
        """
        payload = utils.jwt_payload_handler(self.user)
        payload['exp'] = 1
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        client = APIClient(enforce_csrf_checks=True)
        response = client.post(
            '/auth-token/', self.data,
            HTTP_AUTHORIZATION=auth, format='json')

        self.assertTrue(response.status_code, status.HTTP_200_OK)
 def test_create_refresth_token(self):
     data = {
         'app': 'gandolf'
     }
     self.client.credentials(
         HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler(
             utils.jwt_payload_handler(self.user)))
     response = self.client.post(self.list_url, data, format='json')
     self.assertEqual(
         response.status_code,
         status.HTTP_201_CREATED,
         (response.status_code, response.content)
     )
     self.assertEqual(response.data['user'], self.user.pk)
     self.assertEqual(response.data['app'], data['app'])
Exemplo n.º 46
0
    def authenticate(self, user):
        """
        Authenticates the given user

        :param user: User to authenticate
        :type user: inventorum.ebay.apps.accounts.models.EbayUserModel
        """

        payload = utils.jwt_payload_handler(user)
        self.token = utils.jwt_encode_handler(payload)

        credentials = {
            'HTTP_AUTHORIZATION': 'JWT %s' % self.token
        }
        self.client.credentials(**credentials)
    def test_post_expired_token_failing_jwt_auth(self):
        """
        Ensure POSTing over JWT auth with expired token fails
        """
        payload = utils.jwt_payload_handler(self.user)
        payload["exp"] = 1
        token = utils.jwt_encode_handler(payload)

        auth = "JWT {0}".format(token)
        response = self.csrf_client.post("/jwt/", {"example": "example"}, HTTP_AUTHORIZATION=auth, format="json")

        msg = "Signature has expired."

        self.assertEqual(response.data["detail"], msg)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(response["WWW-Authenticate"], 'JWT realm="api"')
 def test_delete_refresth_token(self):
     self.client.credentials(
         HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler(
             utils.jwt_payload_handler(self.user)))
     response = self.client.delete(self.detail_url)
     self.assertEqual(
         response.status_code,
         status.HTTP_204_NO_CONTENT,
         (response.status_code, response.content)
     )
     response = self.client.delete(self.detail_url1)
     self.assertEqual(
         response.status_code,
         status.HTTP_404_NOT_FOUND,
         (response.status_code, response.content)
     )
    def test_get_refresh_token_list(self):
        self.client.credentials(
            HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler(
                utils.jwt_payload_handler(self.user)))
        response = self.client.get(self.list_url)
        self.assertEqual(len(response.data), 1)
        resp0 = response.data[0]
        self.assertEqual(self.token.key, resp0['key'])

        self.client.force_authenticate(self.user1)
        response = self.client.get(self.list_url)
        self.assertEqual(len(response.data), 1)
        resp0 = response.data[0]
        self.assertEqual(self.token1.key, resp0['key'])

        self.assertEqual(RefreshToken.objects.count(), 2)
    def test_different_auth_header_prefix(self):
        """
        Ensure using a different setting for `JWT_AUTH_HEADER_PREFIX` and
        with correct credentials passes.
        """
        api_settings.JWT_AUTH_HEADER_PREFIX = "Bearer"

        payload = utils.jwt_payload_handler(self.user)
        token = utils.jwt_encode_handler(payload)

        auth = "Bearer {0}".format(token)
        response = self.csrf_client.post("/jwt/", {"example": "example"}, HTTP_AUTHORIZATION=auth, format="json")

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Restore original settings
        api_settings.JWT_AUTH_HEADER_PREFIX = DEFAULTS["JWT_AUTH_HEADER_PREFIX"]
Exemplo n.º 51
0
    def test_post_expired_token_failing_jwt_auth(self):
        """
        Ensure POSTing over JWT auth with expired token fails
        """
        payload = utils.jwt_payload_handler(self.user)
        payload['exp'] = 1
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        response = self.csrf_client.post(
            '/jwt/', {'example': 'example'},
            HTTP_AUTHORIZATION=auth, format='json')

        msg = 'Signature has expired.'

        self.assertEqual(response.data['detail'], msg)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
Exemplo n.º 52
0
    def post(self, request):
        access_token_url = 'https://graph.facebook.com/v2.3/oauth/access_token'
        people_api_url = 'https://graph.facebook.com/v2.3/me'

        payload = dict(client_id=request.data['clientId'],
                       redirect_uri=request.data['redirectUri'],
                       client_secret=settings.SOCIAL_AUTH_FACEBOOK_SECRET,
                       code=request.data['code'],
                       scope='email',
                       )

        # Step 1. Exchange authorization code for access token.
        r = requests.post(access_token_url, data=payload)
        token = json.loads(r.text)
        headers = {'Authorization': 'Bearer {0}'.format(token['access_token']), 'scope': 'email'}

        # Step 2. Retrieve information about the current user.
        r = requests.get(people_api_url, headers=headers)
        profile = json.loads(r.text)

        user = None
        if 'email' in profile:
            try:
                user = User.objects.get(email=profile['email'])
            except User.DoesNotExist:
                pass
        else:
            try:
                user = User.objects.get(email=profile['id'] + '@facebook.com')
            except User.DoesNotExist:
                pass
            profile['email'] = profile['id'] + '@facebook.com'

        if not user:
            user = User.objects.create(username=profile['email'],
                                       first_name=profile['name'].split()[0],
                                       last_name=profile['name'].split()[1],
                                       email=profile['email'])
            Better.objects.create(user=user)

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return Response({'token': token.decode('unicode_escape')},
                        status=status.HTTP_200_OK)
Exemplo n.º 53
0
def generate_token(user):
    """
    Generate a JWT for the user.

    The token generally contains the following:

        {
            "username": "******",
            "orig_iat": 1441902926,
            "user_id": 5,
            "email": "*****@*****.**",
            "exp": 1442507726
        }

    """
    payload = jwt_payload_handler(user)

    return {
        'token': jwt_encode_handler(payload),
    }
    def test_post_form_passing_jwt_auth(self):
        """
        Ensure POSTing form over JWT auth with correct credentials
        passes and does not require CSRF
        """
        payload = utils.jwt_payload_handler(self.user)
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        response = self.csrf_client.post(
            '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.content, b'mockview-post')

        # Ensure `authenticate` returned the decoded payload.
        self.assertEqual(response.wsgi_request.user, self.user)
        payload = response.wsgi_request.auth
        self.assertIsInstance(payload, dict)
        self.assertEqual(set(payload.keys()), {
            'user_id', 'username', 'exp', 'email'})
Exemplo n.º 55
0
    def assert_jwt_status(self, issuer=None, expires=None, status_code=200):
        """Assert that the payload has a valid issuer and has not expired."""
        staff_user = self.create_user(is_staff=True)
        issuer = issuer or settings.JWT_AUTH['JWT_ISSUERS'][0]

        payload = {
            'iss': issuer,
            'username': staff_user.username,
            'email': staff_user.email,
            'full_name': staff_user.full_name
        }

        if expires:
            payload['exp'] = expires

        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        response = self.client.get('/jwt/', HTTP_AUTHORIZATION=auth)

        self.assertEqual(response.status_code, status_code)
Exemplo n.º 56
0
    def assert_jwt_status(self, issuer=None, expires=None, status_code=200):
        """ Assert that the payload has a valid issuer and has not expired. """

        staff_user = self.create_user(is_staff=True)
        issuer = issuer or settings.JWT_ISSUERS[0]

        payload = {
            "iss": issuer,
            "username": staff_user.username,
            "email": staff_user.email,
            "full_name": staff_user.full_name,
        }

        if expires:
            payload["exp"] = expires

        token = utils.jwt_encode_handler(payload)

        auth = "JWT {0}".format(token)
        response = self.client.get("/jwt/", HTTP_AUTHORIZATION=auth)

        self.assertEqual(response.status_code, status_code)
Exemplo n.º 57
0
 def post(self, request):
     serialized = UserSerializer(data=request.DATA)
     if serialized.is_valid():
         try:
             User.objects.get(email=serialized.data['email'])
             return Response({'error': 'User with same email already exists.'},
                             status=status.HTTP_400_BAD_REQUEST)
         except User.DoesNotExist:
             pass
         user = User.objects.create_user(
             serialized.data['username'],
             serialized.data['email'],
             serialized.data['password'],
             first_name=serialized.data['username']
         )
         Better.objects.create(user=user)
         payload = jwt_payload_handler(user)
         token = jwt_encode_handler(payload)
         return Response({'token': token.decode('unicode_escape')},
                         status=status.HTTP_201_CREATED)
     else:
         return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 58
0
    def post(self, request):
        access_token_url = 'https://graph.facebook.com/v2.4/oauth/access_token'
        people_api_url = 'https://graph.facebook.com/v2.4/me?fields=id,email,name'

        payload = dict(client_id=request.data['clientId'],
                       redirect_uri=request.data['redirectUri'],
                       client_secret=settings.SOCIAL_AUTH_FACEBOOK_SECRET,
                       code=request.data['code'],
                       scope='email',
                       )

        # Step 1. Exchange authorization code for access token.
        r = requests.post(access_token_url, data=payload)
        token = json.loads(r.text)
        headers = {'Authorization': 'Bearer {0}'.format(token['access_token']), 'scope': 'email'}

        # Step 2. Retrieve information about the current user.
        r = requests.get(people_api_url, headers=headers)
        profile = json.loads(r.text)

        user = self.get_or_create_user(profile)
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return Response({'token': token.decode('unicode_escape')}, status=status.HTTP_200_OK)