コード例 #1
0
 def post(request, **kwargs):
     serializer = UserLoginSerializer(data=request.data)
     if serializer.is_valid():
         phone = serializer.validated_data.get('phone')
         if re.match('^((\+38|\+7|\+8)+([0-9]){10})$', phone):
             one_time_password = random.randint(10000, 99999)
             try:
                 user = User.objects.get(phone=phone)
                 sms_text = f'Войдите, используя код: {one_time_password}'
             except User.DoesNotExist:
                 user = User.objects.create(phone=phone)
                 Token.objects.create(user=user)
                 sms_text = f'Вы были успешно зарегестрированы!\nВойдите, используя код: {one_time_password}'
             user.set_password(one_time_password)
             user.save()
             send_sms_code(phone, sms_text)
             return Response({
                 'success': f'Code was sent by number {phone}.',
             }, status=status.HTTP_200_OK)
         return Response({
             'error': 'Number is not in russian number format!',
         }, status=status.HTTP_400_BAD_REQUEST)
     return Response({
         'error': 'Phone is required!',
     }, status=status.HTTP_400_BAD_REQUEST)
コード例 #2
0
 def post(self, request, *args, **kwargs):
     data = request.data
     serializer = UserLoginSerializer(data=data)
     if serializer.is_valid(raise_exception=True):
         new_data = serializer.data
         return Response(new_data, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
コード例 #3
0
 def login(self, request):
     """Inicio de sesion de Usuarios."""
     serializer = UserLoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user, token = serializer.save()
     data = {'user': UserModelSerializer(user).data, 'access_token': token}
     return Response(data, status=status.HTTP_200_OK)
コード例 #4
0
ファイル: views.py プロジェクト: balrammirani/NewsFeed
 def post(self, request, *args, **kwargs):
     data = request.data
     serializer = UserLoginSerializer(data=data)
     if serializer.is_valid(raise_exception=True):
         new_data = serializer.data
         return Response(new_data, status=HTTP_200_OK)
     return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
コード例 #5
0
    def login(self, request):
        """User sign in."""
        print(request.data)
        # First clear everything before login
        logout(request)
        serializer = UserLoginSerializer(data=request.data)

        if not serializer.is_valid(raise_exception=False):
            data = {
                "info": "password or username are not valid",
                "failure": "validation failed",
            }

            return Response(data, status=status.HTTP_403_FORBIDDEN)

        user, token = serializer.save()

        data = {
            "info": "success validation",
            "success": "user validated",
            "user": UserModelSerializer(user).data,
            "access_token": token,
        }

        response = Response(data, status=status.HTTP_201_CREATED)

        # Use default django authentication
        login(request, user)

        return response
コード例 #6
0
ファイル: views.py プロジェクト: Minesto23/api-curriculum
 def login(self, request):
     """User sign in."""
     serializer = UserLoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user, token = serializer.save()
     data = {'user': UserModelSerializer(user).data, 'access_token': token}
     return Response(data, status=status.HTTP_201_CREATED)
コード例 #7
0
ファイル: views.py プロジェクト: EveFer/backend-users-test
 def login(self, request):
     """Instructor Login"""
     serializer = UserLoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     token = serializer.save()
     data = {
         'access_token': token
     }
     return Response(data, status=status.HTTP_201_CREATED)
コード例 #8
0
    def post(self, request):
        serializer = UserLoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = UserSerializer(serializer.user).data
        data['token'] = login_user(self.request, serializer.user).key

        # See if the user belongs to PreUserGroup and add him
        check_source_and_add_user_to_group(request, serializer.user)

        return Response(data, status=status.HTTP_200_OK)
コード例 #9
0
    def test_userloginserializer_missing_fields(self):
        """Checks User instance login using UserLoginSerializer

        Test if UserLoginSerializer deserialization is invalid due to missing
        mandatory field."""
        data = {}
        serializer = UserLoginSerializer(data=data)
        self.assertFalse(
            serializer.is_valid(),
            msg="""User deserialization should not be valid since the email and
            password fields are missing.""")
        self.assertIn('non_field_errors', serializer.errors)
        self.assertEqual(str(serializer.errors.get('non_field_errors')[0]),
                         MISSING_FIELD_ERROR)

        data = {'email': self.email}
        serializer = UserLoginSerializer(data=data)
        self.assertFalse(
            serializer.is_valid(),
            msg="""User deserialization should not be valid since the password
            field is missing.""")
        self.assertIn('non_field_errors', serializer.errors)
        self.assertEqual(str(serializer.errors.get('non_field_errors')[0]),
                         MISSING_FIELD_ERROR)

        data = {'password': self.password}
        serializer = UserLoginSerializer(data=data)
        self.assertFalse(
            serializer.is_valid(),
            msg="""User deserialization should not be valid since the email
            field is missing.""")
        self.assertIn('non_field_errors', serializer.errors)
        self.assertEqual(str(serializer.errors.get('non_field_errors')[0]),
                         MISSING_FIELD_ERROR)
コード例 #10
0
    def post(self, request):
        
        login_serializer = UserLoginSerializer(data=request.data)
        login_serializer.is_valid(raise_exception=True)

        user = authenticate(
            email=request.data.get('email'),
            password=request.data.get('password')
        )
        login(request, user)

        return Response(data=login_serializer.data, status=status.HTTP_200_OK)
コード例 #11
0
    def test_userloginserializer_email_not_registered(self):
        """Checks User instance login using UserLoginSerializer

        Test if UserLoginSerializer deserialization is invalid due email not in
        the database."""
        data = {'email': '*****@*****.**', 'password': '******'}
        serializer = UserLoginSerializer(data=data)
        self.assertFalse(
            serializer.is_valid(),
            msg="""User deserialization should not be valid since the email
            does not belong to any user.""")
        self.assertIn('non_field_errors', serializer.errors)
        self.assertEqual(str(serializer.errors.get('non_field_errors')[0]),
                         INVALID_LOGIN_ERROR)
コード例 #12
0
    def test_userloginserializer_invalid_credentials(self):
        """Checks User instance login using UserLoginSerializer

        Test if UserLoginSerializer deserialization is invalid due invalid
        credentials."""
        data = {'email': self.email, 'password': '******'}
        serializer = UserLoginSerializer(data=data)
        self.assertFalse(
            serializer.is_valid(),
            msg="""User deserialization should not be valid since the password
            is wrong.""")
        self.assertIn('non_field_errors', serializer.errors)
        self.assertEqual(str(serializer.errors.get('non_field_errors')[0]),
                         INVALID_LOGIN_ERROR)
コード例 #13
0
ファイル: views.py プロジェクト: ignatowski/mastermind
 def post(self, request: Dict, format: str = 'json') -> Response:
     """Login user."""
     # serialize the request body
     serializer = UserLoginSerializer(data=request.data)
     # check that the request data was valid
     if serializer.is_valid():
         # get the logged in user
         user = serializer.user
         if user:
             # get the user's existing auth token or generate a new one
             token, _ = Token.objects.get_or_create(user=user)
             json = serializer.data
             json['token'] = token.key
             return Response(json, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
コード例 #14
0
ファイル: users.py プロジェクト: albertoaldanar/betmatcherAPI
    def login(self, request):
        notification_token = request.query_params.get("notification_token")
        current_user_param = request.data["username"]
        current_user = User.objects.get(username=current_user_param)

        profile = current_user.profile

        profile.notification_token = notification_token
        profile.save()

        serealizer = UserLoginSerializer(data=request.data)
        serealizer.is_valid(raise_exception=True)
        user, token = serealizer.save()

        data = {"user": UserModelSerializer(user).data, "jwt": token}
        return Response(data, status=status.HTTP_201_CREATED)
コード例 #15
0
ファイル: views.py プロジェクト: klpdotorg/ilp
 def post(self, request):
     serializer = UserLoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     data = UserSerializer(serializer.user).data
     user = authenticate(request, username=request.data["username"], password=request.data["password"])
     if user is not None:
         login(self.request, user)
         # See if the user belongs to PreUserGroup and add him
         # check_source_and_add_user_to_group(request, serializer.user)
         if user.is_staff:
             print("user is a staff")
             print(request.GET.get('next', '/backoffice/'))
             return HttpResponseRedirect(request.GET.get('next', '/backoffice/'))
         else:
             return Response("User forbidden access to this area", status=status.HTTP_403_FORBIDDEN)
     else:
             return Response("Invalid Login", status=status.HTTP_401_UNAUTHORIZED)
コード例 #16
0
 def post(request):
     user = get_object_or_404(CustomUser, email=request.data.get('email'))
     user = authenticate(email=user.email,
                         password=request.data.get('password'))
     if user:
         serializer = UserLoginSerializer(user)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response()
コード例 #17
0
    def post(self, request):

        copy_data = request.data.copy()
        copy_data['type'] = request.path.split("/")[-3]
        if (request.data.get('type') != None):
            copy_data['social'] = request.data['type']

        serializer = UserLoginSerializer(data=copy_data)
        serializer.is_valid(raise_exception=True)
        user, token = serializer.save()
        data = {
            'user':
            ClientAllSerializer(user).data
            if copy_data['type'] == 'client' else WorkerSerializer(user).data,
            'access_token':
            token
        }
        return Response(data)
コード例 #18
0
 def post(self, request):
     login_serializer = UserLoginSerializer(
         data=request.data.get('login_data'))
     login_serializer.is_valid(raise_exception=True)
     user = login_serializer.validated_data.get('user')
     if user:
         login(request, user)
         user_serializer = UserSerializer(
             user,
             context={
                 'data': {
                     'fields':
                     ['first_name', 'last_name', 'email', 'token']
                 }
             })
         return Response({'success': True, 'user': user_serializer.data})
     return Response({
         'success': False,
         'error': "Unable to login with given credentials"
     })
コード例 #19
0
 def test_login_required_date(self):
     """ Заполнена только основная информация"""
     user_data = {
         'username': '******',
         'name': 'test_user',
         'email': '*****@*****.**'
     }
     user = User(**user_data)
     user.set_password('StrongPassword123')
     user.save()
     data = UserLoginSerializer(user).data
     expected_data = {'username': '******', 'password': user.password}
     self.assertEqual(expected_data, data)
コード例 #20
0
    def test_userloginserializer_token_generation(self):
        """Checks User instance login using UserLoginSerializer

        Test if UserLoginSerializer deserialization is valid."""
        time_before_login = timezone.now()
        data = {'email': self.email, 'password': self.password}
        serializer = UserLoginSerializer(data=data)
        self.assertTrue(
            serializer.is_valid(),
            msg="""User deserialization should be valid since the credentials
            are correct.""")

        serializer_data = serializer.save()
        user_data = serializer_data.get('user')

        for key in ['email', 'first_name', 'last_name']:
            self.assertIn(
                key,
                user_data.keys(),
                msg="""UserLoginSerializer did not return {} information.""".
                format(key))

            value = user_data[key]
            expected_value = getattr(self.user, key)
            self.assertEqual(
                value,
                expected_value,
                msg="""UserLoginSerializer returned incorrect {} information.
                Expected: {}. Obtained: {}""".format(key, expected_value,
                                                     value))

        last_login = user_data.get('last_login')
        last_login = datetime.strptime(last_login, '%Y-%m-%dT%H:%M:%S%f%z')
        self.assertGreater(
            last_login,
            time_before_login,
            msg="""UserLoginSerializer returned incorrect last_login
            information. Expected: {}. Obtained: {}""".format(
                time_before_login, last_login))
コード例 #21
0
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data)
     try:
         serializer.is_valid(raise_exception=True)
     except:
         return Response(
             messages.bad_login, status=status.HTTP_400_BAD_REQUEST)
     user = serializer.validated_data['user']
     token = Token.objects.filter(user=user).first()
     if not token:
         return Response(
             messages.inactive, status=status.HTTP_403_FORBIDDEN)
     serializer = UserLoginSerializer(user)
     return Response(serializer.data, status=status.HTTP_200_OK)
コード例 #22
0
ファイル: tadaviews.py プロジェクト: rjshrjndrn/ilp
 def post(self, request):
     serializer = UserLoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     data = TadaUserSerializer(serializer.user).data
     data['token'] = login_user(self.request, serializer.user).key
     return Response(data, status=status.HTTP_200_OK)
コード例 #23
0
    def post(self, request):
        """
            :param
            {
                    "email" : "*****@*****.**",
                    "password": 123456
            }

            :return
            'Failure'
                For invalid request
                {
                    "error": true,
                    "message": "Bad Request",
                    "data": {
                        "email": [
                            "This field may not be blank."
                        ]
                    }
                }
                {
                    "error": true,
                    "message": "Bad Request",
                    "data": {
                        "email": [
                            "Enter a valid email address."
                        ]
                    }
                }
                for an email not registered
                {
                    "error": true,
                    "message": "Account does not exist with given email address",
                    "data": {}
                }
            'Success'
                {
                    "error": false,
                    "message": "Login Successfully",
                    "data": {
                        "user": {
                            "id": 10,
                            "last_login": "******",
                            "first_name": "hiren",
                            "last_name": "patel",
                            "email": "*****@*****.**",
                            "username": null,
                            "is_email_verified": false,
                            "created_at": "2020-07-10T06:50:07.887012Z",
                            "updated_at": "2020-07-10T06:50:08.031816Z"
                        },
                        "token": "6a424722d7de3a91c72379c4ed966c136362fcce"
                    }
                }
        """

        serializer = UserLoginSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    'error': True,
                    'message': "Bad Request",
                    'data': serializer.errors
                },
                status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=request.data['email'])
        except User.DoesNotExist:
            return Response(
                {
                    'error': True,
                    'message':
                    "Account does not exist with given email address",
                    'data': {}
                },
                status=status.HTTP_400_BAD_REQUEST)

        if user.check_password(request.data['password']):

            token = Token.objects.get(user_id=user.id)
            user_serializer = UserSerializer(user)

            return Response(
                {
                    'error': False,
                    'message': "Login Successfully",
                    'data': {
                        'user': user_serializer.data,
                        'token': token.key
                    }
                },
                status=status.HTTP_200_OK)

        else:
            return Response(
                {
                    'error': True,
                    'message': "Invalid Credential",
                    'data': {}
                },
                status=status.HTTP_401_UNAUTHORIZED)