def post(request):
     try:
         serializer = JSONWebTokenSerializer(data=request.data)
         if serializer.is_valid():
             serialized_data = serializer.validate(request.data)
             # from custom_logger import DatabaseCustomLogger
             # d = DatabaseCustomLogger()
             # d.database_logger(123)
             user = User.objects.get(email=request.data.get('email'))
             return Response(
                 {
                     'status': True,
                     'token': serialized_data['token'],
                 },
                 status=status.HTTP_200_OK)
         else:
             message = ''
             for error in serializer.errors.values():
                 message += " "
                 message += error[0]
             return Response({
                 'status': False,
                 'message': message
             },
                             status=status.HTTP_400_BAD_REQUEST)
     except (AttributeError, ObjectDoesNotExist):
         return Response({
             'status': False,
             'message': "User does not exist"
         },
                         status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
    def post(request):

        try:
            serializer = JSONWebTokenSerializer(data=request.data)
            if serializer.is_valid():
                serialized_data = serializer.validate(request.data)
                # from custom_logger import DatabaseCustomLogger
                # d = DatabaseCustomLogger()
                # d.database_logger(123)
                email = request.data.get('email')
                user = User.objects.get(email=email)
                # if not user.is_email_verified:
                #     return Response({
                #         'status': False,
                #         'data': "Email Verification is pending",
                #     }, status=status.HTTP_200_OK)
                user_serializer = UserListSerializer(user)
                return Response({
                    'status': True,
                    'token': serialized_data['token'],
                    'data': user_serializer.data,
                }, status=status.HTTP_200_OK)
            else:
                message = ''
                for error in serializer.errors.values():
                    message += " "
                    message += error[0]
                return Response({'status': False,
                                 'message': message},
                                status=status.HTTP_400_BAD_REQUEST)
        except (AttributeError, ObjectDoesNotExist):
            return Response({'status': False,
                             'message': "User doesnot exists"},
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #3
0
    def post(request):
        try:
            serializer = JSONWebTokenSerializer(data=request.data)
            if serializer.is_valid():
                serializer_data = serializer.validate(request.data)

                user = CustomUser.objects.get(
                    username=request.data.get('username'))
                return Response(
                    {
                        'status': True,
                        'token': serializer_data['token']
                    },
                    status=status.HTTP_200_OK)
            else:
                message = ''
                for error in serializer.errors.values():
                    message += " "
                    message += error[0]
                return Response({
                    'status': False,
                    'message': message
                },
                                status=status.HTTP_400_BAD_REQUEST)
        except (AttributeError, ObjectDoesNotExist):
            return Response({
                'status': False,
                'message': 'User does not exist'
            },
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #4
0
 def create(self, request, *args, **kwargs):
     """
     Register a User.
     If the user information already exists, an error will be returned.
     """
     serializer = UserRegisterSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         auth_classes = getattr(settings, "REST_FRAMEWORK",
                                {}).get("DEFAULT_AUTHENTICATION_CLASSES",
                                        [])
         # TODO: ultimately should have a configurable "preferred" auth method
         if "rest_framework_jwt.authentication.JSONWebTokenAuthentication" in auth_classes:
             username_field = get_user_model().USERNAME_FIELD
             username = serializer.data.get(username_field)
             password = request.data.get("password")
             token_data = {"password": password}
             token_data[username_field] = username
             token_serializer = JSONWebTokenSerializer(data=token_data)
             if token_serializer.is_valid():
                 return Response(
                     {"token": token_serializer.object.get('token')},
                     status=status.HTTP_201_CREATED)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #5
0
    def post(self, *args, **kwargs):
        try:
            graph = GraphAPI(access_token=self.request.data['access_token'],
                             version=settings.FACEBOOK_APP_VERSION)
            graph_data = graph.get_object(id='me',
                                          fields='email,first_name,last_name')
        except GraphAPIError:
            raise ParseError(detail='Invalid Facebook access token')

        data = {
            **graph_data, 'password':
            get_user_model().objects.make_random_password()
        }

        user, created = get_user_model().objects.get_or_create(
            email=data['email'])
        signup_ser = SignUpSerializer(instance=user, data=data)
        signup_ser.is_valid(raise_exception=True)

        user = signup_ser.save(is_active=True)

        token_ser = JSONWebTokenSerializer(data={
            'email': data['email'],
            'password': data['password']
        })
        token_ser.is_valid(raise_exception=True)

        HistoryRecord.objects.create_history_record(
            user, None, HISTORY_RECORD_USER_SIGNUP_FACEBOOK)

        return Response(
            {'token': token_ser.object.get('token')},
            status=status.HTTP_201_CREATED if created else status.HTTP_200_OK)
Exemple #6
0
    def test_create(self):
        serializer = JSONWebTokenSerializer(data=self.data)
        is_valid = serializer.is_valid()

        token = serializer.object['token']
        decoded_payload = utils.jwt_decode_handler(token)

        self.assertTrue(is_valid)
        self.assertEqual(decoded_payload['username'], self.username)
    def test_create(self):
        serializer = JSONWebTokenSerializer(data=self.data)
        is_valid = serializer.is_valid()

        token = serializer.object['token']
        decoded_payload = utils.jwt_decode_handler(token)

        self.assertTrue(is_valid)
        self.assertEqual(decoded_payload['username'], self.username)
Exemple #8
0
def get_authenticated_user_client():
    client = APIClient()
    User.objects.create_user(email="*****@*****.**", password="******")
    serializer = JSONWebTokenSerializer()
    attrs = {
        'email': '*****@*****.**',
        'password': '******',
    }
    user_credential = serializer.validate(attrs)
    client.credentials(HTTP_AUTHORIZATION='Bearer ' + user_credential.get('token'))
    return client
Exemple #9
0
    def test_invalid_credentials(self):
        self.data['password'] = '******'
        serializer = JSONWebTokenSerializer(data=self.data)
        is_valid = serializer.is_valid()

        expected_error = {
            'non_field_errors': ['Unable to login with provided credentials.']
        }

        self.assertFalse(is_valid)
        self.assertEqual(serializer.errors, expected_error)
    def test_invalid_credentials(self):
        self.data['password'] = '******'
        serializer = JSONWebTokenSerializer(data=self.data)
        is_valid = serializer.is_valid()

        expected_error = {
            'non_field_errors': ['Unable to login with provided credentials.']
        }

        self.assertFalse(is_valid)
        self.assertEqual(serializer.errors, expected_error)
    def test_required_fields(self):
        serializer = JSONWebTokenSerializer(data={})
        is_valid = serializer.is_valid()

        expected_error = {
            'username': ['This field is required.'],
            'password': ['This field is required.']
        }

        self.assertFalse(is_valid)
        self.assertEqual(serializer.errors, expected_error)
    def test_disabled_user(self):
        self.user.is_active = False
        self.user.save()

        serializer = JSONWebTokenSerializer(data=self.data)
        is_valid = serializer.is_valid()

        expected_error = {'non_field_errors': ['User account is disabled.']}

        self.assertFalse(is_valid)
        self.assertEqual(serializer.errors, expected_error)
Exemple #13
0
 def post(self, request):
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.save()
     password = self.request.data.get("password")
     token_serializer = JSONWebTokenSerializer(data={"username": user.username, "password": password})
     token_serializer.is_valid(raise_exception=True)
     res = {
         "token": token_serializer.validated_data.get("token"),
     }
     return Response(res, status=status.HTTP_201_CREATED)
Exemple #14
0
 def mutate_and_get_payload(cls, input, context, info):
     serializer = JSONWebTokenSerializer(data=input)
     if serializer.is_valid():
         token = serializer.object['token']
         user = serializer.object['user']
         return Login(success=True, user=user, token=token, errors=None)
     else:
         return Login(
             success=False,
             token=None,
             errors=['email', 'Unable to login with provided credentials.'])
Exemple #15
0
def login_request(request, format=None):
    seria = JSONWebTokenSerializer(data=request.data)
    seria.is_valid(raise_exception=True)
    user = seria.object.get('user')
    if user is None:
        return Response('', status=status.HTTP_404_NOT_FOUND)
    token = seria.object.get('token')
    info = CoinUserInfo.objects.filter(user=user.id).first()
    response_data = CoinUserInfoSerializer(info).data
    response_data['token'] = token
    return Response(response_data)
Exemple #16
0
    def test_required_fields(self):
        serializer = JSONWebTokenSerializer(data={})
        is_valid = serializer.is_valid()

        expected_error = {
            'username': ['This field is required.'],
            'password': ['This field is required.']
        }

        self.assertFalse(is_valid)
        self.assertEqual(serializer.errors, expected_error)
Exemple #17
0
    def test_disabled_user(self):
        self.user.is_active = False
        self.user.save()

        serializer = JSONWebTokenSerializer(data=self.data)
        is_valid = serializer.is_valid()

        expected_error = {
            'non_field_errors': ['User account is disabled.']
        }

        self.assertFalse(is_valid)
        self.assertEqual(serializer.errors, expected_error)
Exemple #18
0
 def mutate_and_get_payload(cls, input, context, info):
     user = {'email': input['email'], 'password': input['password']}
     serializer = JSONWebTokenSerializer(data=user)
     if serializer.is_valid():
         token = serializer.object['token']
         user = serializer.object['user']
         return Login(success=True, user=user, token=token, errors=None)
     else:
         return Login(
             success=False,
             token=None,
             errors=['email', 'Unable to login with provided credentials.']
         )
Exemple #19
0
def login_request(request, format=None):
    s = JSONWebTokenSerializer(data=request.data)
    try:
        s.is_valid(raise_exception=True)
        user = s.object.get('user')
    except (ValidationError, CoinUser.DoesNotExist):
        return Response('请输入正确的用户名和密码',)
    token = s.object.get('token')
    info = CoinUserInfo.objects.filter(user=user.id).first()
    response_data = CoinUserInfoSerializer(info).data
    response_data['token'] = token
    response_data['code'] = user.code
    return Response(response_data, status=status.HTTP_201_CREATED)
Exemple #20
0
    def post(self, request):
        sms = request.data.pop('sms_code')
        redis_cli = get_redis_connection('sms')
        sms_code = redis_cli.get(request.data.get('mobile'))
        if sms_code.decode() != sms:
            return Response({'data': {'success': False, 'message': '验证码错误'}})
        serializer = UserSerializer(data=request.data)
        serializer.is_valid()
        user = serializer.save()
        serializer_jwt = JSONWebTokenSerializer(data=request.data)
        token = serializer_jwt.validate(request.data).get('token')
        data = jwt_response_payload_handler(token, user, request)

        return Response(data)
Exemple #21
0
    def post(self, request, *args, **kwargs):
        serializer = JSONWebTokenSerializer(data=request.data)

        # raise_exception=True,保证异常被handle_exception()处理
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data.get('user') or request.user
        token = serializer.object.get('token')
        response_data = {
            'user': UserSerializer(user).data,
            'token': token,
            }
        user.last_login = timezone.now()
        user.save()
        return Response(response_data, status=status.HTTP_200_OK)
Exemple #22
0
def autenticar_usuario(message_json):
    user = message_json['user']
    password = message_json['password']

    serializer_data = {'data': {'cc': user, 'password': password}}
    jwt_serializer = JSONWebTokenSerializer(**serializer_data)
    if jwt_serializer.is_valid():
        user = jwt_serializer.object.get('user')
        token = jwt_serializer.object.get('token')
    else:
        return json.dumps({'error': True})

    respuesta = {'token': token, 'user': UserSerializer(user).data}
    respuesta = json.dumps(respuesta)
    return respuesta
Exemple #23
0
 def mutate_and_get_payload(cls, root, info, **input):
     user = {'email': input['email'], 'password': input['password']}
     serializer = JSONWebTokenSerializer(data=user)
     if serializer.is_valid():
         token = serializer.object['token']
         user = serializer.object['user']
         return Login(success=True, user=user, token=token, errors=None)
     else:
         return Login(success=False,
                      token=None,
                      errors=[
                          'email',
                          u'Non è possibile eseguire il login con le '
                          u'credenzili fornite.'
                      ])
Exemple #24
0
    def post(self, request, format=None):

        serializer = JSONWebTokenSerializer(data=request.DATA)

        if serializer.is_valid():
            token = serializer.object['token']
            pay_load = jwt_decode_handler(token)

            return Response({
                'token' : token,
                'expire' : datetime.fromtimestamp(pay_load['exp'])
                }, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    def test_empty_drf2(self):
        serializer = JSONWebTokenSerializer()
        expected = {
            'username': ''
        }

        self.assertTrue(serializer.data, expected)
Exemple #26
0
 def post(request):
     serializer = JSONWebTokenSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     serialized_data = serializer.validate(request.data)
     user_data = UserSerializer(
         User.objects.get(username=request.data['username'])).data
     if not user_data['groups']:
         return Response({'groups': "User not registered with any groups."},
                         status=status.HTTP_400_BAD_REQUEST)
     return Response(
         {
             'status': True,
             'token': serialized_data['token'],
             'user': user_data,
         },
         status=status.HTTP_200_OK)
Exemple #27
0
 def test_fields(self):
     serializer = JSONWebTokenSerializer()
     self.assert_fields_required(True, serializer, self.required_fields)
     self.assert_fields_required(False, serializer,
                                 self.not_required_fields)
     self.assertEqual(
         len(serializer.fields),
         len(self.required_fields) + len(self.not_required_fields))
    def test_empty_drf3(self):
        serializer = JSONWebTokenSerializer()
        expected = {
            'username': '',
            'password': ''
        }

        self.assertEqual(serializer.data, expected)
def authenticate_user(client, user, admin_user=False, serializer_class=None):
    if admin_user:
        user.is_superuser = True
        user.save()

    serializer = JSONWebTokenSerializer()
    if serializer_class:
        serializer = serializer_class()

    attrs = {
        user.USERNAME_FIELD: user.get_username(),
        "password": "******",
    }
    user_credential = serializer.validate(attrs)
    client.credentials(HTTP_AUTHORIZATION="Bearer " +
                       user_credential.get("token"))
    return client
Exemple #30
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     wx_api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET)
     data = serializer.data
     try:
         session_info = wx_api.exchange_code_for_session_key(data['code'])
     except Exception as e:
         logger.warning("exchange code error:{}".format(e))
         return Response(data={"code": ["登录失败"]},
                         status=status.HTTP_400_BAD_REQUEST)
     if session_info:
         openid = session_info['openid']
         user, _ = User.objects.get_or_create(
             defaults={"password": make_password(PASSWORD)},
             username=openid)
         user_profile, _ = Consumer.objects.update_or_create(
             user=user,
             defaults={
                 'openid': openid,
                 'session_key': session_info['session_key'],
                 'user_name': data['user_name'],
                 "sex": data['sex'],
                 "avatar_url": data['avatar_url']
             })
         if data.get("sell_user"):
             # if data.get("recommend_id") and not user_profile.sell_user:
             sell_user = Consumer.objects.get(id=data.get("sell_user"))
             user_profile.sell_user = sell_user
             user_profile.save()
             logger.info("user_id:{}, sell_user_id:{}".format(
                 user_profile, sell_user))
         serializer = JSONWebTokenSerializer(data={
             "username": openid,
             "password": PASSWORD
         })
         serializer.is_valid(raise_exception=True)
         user = serializer.object.get("user") or request.user
         token = serializer.object.get("token")
         response_data = jwt_response_payload_handler(token, user, request)
         return Response(response_data, status=status.HTTP_200_OK)
     return Response(data={"code": ['认证异常']},
                     status=status.HTTP_400_BAD_REQUEST)
Exemple #31
0
 def create(self, request, *args, **kwargs):
     username = request.data["username"]
     password = request.data["password"]
     keys = red_user_cache.keys()
     try:
         for single_key in keys:
             user_info = red_user_cache.get(single_key)
             redis_username, redis_password, redis_email = json.loads(
                 user_info)
             if redis_username == username:
                 return Response({"non_field_errors": ["账号未激活,请先激活账号"]},
                                 status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         pass
     user = User.objects.filter(username=username).first()
     if not user:
         return Response({"non_field_errors": ["账号或者密码错误"]},
                         status=status.HTTP_400_BAD_REQUEST)
     if not user.check_password(password):
         return Response({"non_field_errors": ["账号或者密码错误"]},
                         status=status.HTTP_400_BAD_REQUEST)
     if not user.has_active:
         return Response({"non_field_errors": ["账号未激活,请先激活账号"]},
                         status=status.HTTP_400_BAD_REQUEST)
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     #采用jwt模式认证
     serializer_instance = JSONWebTokenSerializer(data=request.data)
     if serializer_instance.is_valid():
         user = serializer_instance.object.get('user') or request.user
         token = serializer_instance.object.get('token')
         response_data = jwt_response_payload_handler(token, user, request)
         response = Response(response_data)
         if api_settings.JWT_AUTH_COOKIE:
             expiration = (datetime.utcnow() +
                           api_settings.JWT_EXPIRATION_DELTA)
             response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                 token,
                                 expires=expiration,
                                 httponly=True)
         return response
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #32
0
def create_auth(request):
    serialized = UserProfileSerializer(data=request.data)
    jwt = JSONWebTokenSerializer(data=request.data)
    data = jwt.is_valid()
    if serialized.is_valid():
        serialized.save()
        result = {
            "success": True,
            "sessionId": jwt.validate(request.data)["token"]
        }
        code = status.HTTP_201_CREATED
    else:
        code = status.HTTP_400_BAD_REQUEST
        result = {
            "success": False,
            "message": "Wrong request data",
            "details": str(serialized._errors),
            "code": code
        }
    return Response(result, status=code)
Exemple #33
0
 def create(self, request, *args, **kwargs):
     """
     Register a User.
     If the user information already exists, an error will be returned.
     """
     serializer = UserRegisterSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         auth_classes = getattr(settings, "REST_FRAMEWORK", {}).get("DEFAULT_AUTHENTICATION_CLASSES", [])
         # TODO: ultimately should have a configurable "preferred" auth method
         if "rest_framework_jwt.authentication.JSONWebTokenAuthentication" in auth_classes:
             username_field = get_user_model().USERNAME_FIELD
             username = serializer.data.get(username_field)
             password = request.data.get("password")
             token_data = {"password": password}
             token_data[username_field] = username
             token_serializer = JSONWebTokenSerializer(data=token_data)
             if token_serializer.is_valid():
                 return Response({"token": token_serializer.object.get('token')}, status=status.HTTP_201_CREATED)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #34
0
    def post(self, request):
        validated = RegistrationSerializer(data=request.data)
        validated.is_valid(True)
        if User.objects.filter(
                username=validated.validated_data["email"]
        ).exists():
            raise ParseError("User with this email is exists")
        try:
            stripe_customer = stripe.Customer.create(
                email=validated.validated_data["email"],
                source=validated.validated_data["stripe_token"]
            )
        except stripe.error.InvalidRequestError:
            raise ParseError("Invalid stripe token")

        user = User(
            email=validated.validated_data["email"],
            username=validated.validated_data["email"],
            is_subscriber=True
        )
        user.set_password(validated.validated_data["password"])
        user.stripe_token = stripe_customer.get('id')
        user.save()
        stripe_subscription = stripe.Subscription.create(
            customer=stripe_customer.id,
            items=[
                {
                    "plan": STRIPE_PLAN,
                },
            ]
        )
        Subscription.objects.create(
            user=user,
            stripe_token=stripe_subscription.id,
            till=datetime.fromtimestamp(
                stripe_subscription.current_period_end
            )
        )
        token = JSONWebTokenSerializer().validate(
            {
                "username": user.username,
                "password": validated.validated_data["password"]
            }
        ).get("token")
        self.registration_email(email=user.email, token=token)
        return Response({"token": token})
Exemple #35
0
 def get_jwt_token(self):        
     serializer = JSONWebTokenSerializer(
         data={'email': self.user.email, 'password': '******'})
     serializer.is_valid()
     token = serializer.object['token']
     return "JWT %s" % token
 def get_serializer(self, **kwargs):
     serializer = JSONWebTokenSerializer(**kwargs)
     serializer.context['request'] = Request(HttpRequest()),
     return serializer
def token(user):
    serializer = JSONWebTokenSerializer(
        data={'email': user.email, 'password': '******'})
    serializer.is_valid()
    token = serializer.object['token']
    return "JWT %s" % token