예제 #1
0
 def post(self, request, *args, **kwargs):
     serializer = LoginSerializer(data=request.DATA)
     if serializer.is_valid():
         login(request, serializer.user_cache)
         if not serializer.data['remember']:
             request.session.set_expiry(0)
         return Response({'success': True})
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #2
0
 def post(self, request, *args, **kwargs):
     serializer = LoginSerializer(data=request.DATA)
     if serializer.is_valid():
         login(request, serializer.user_cache)
         if not serializer.data['remember']:
             request.session.set_expiry(0)
         return Response({'success': True})
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #3
0
파일: views.py 프로젝트: Drolegc/a_pedal
    def post(self, request, *args, **kwargs):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.save()

        data = {
            'token': token,
        }

        return Response(data, status=status.HTTP_201_CREATED)
예제 #4
0
    def login(self, request, *args, **kwargs):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user: User = serializer.validated_data.get('user')
        token, _ = Token.objects.get_or_create(user=user)

        return Response({
            'user': UserSerializer(user).data,
            'token': token.key
        }, status.HTTP_201_CREATED)
예제 #5
0
파일: users.py 프로젝트: jpcano1/tShoes
    def login(self, request):
        """

            :param request:
            :return:
        """
        serializer = LoginSerializer(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)
    def test_invalid_credentials(self):
        data = {
            'email': '*****@*****.**',
            'password': '******',
        }
        serializer = LoginSerializer(data=data)

        self.assertFalse(serializer.is_valid())
        self.assertDictEqual(
            serializer.errors, {
                'non_field_errors':
                [ErrorDetail(string='Invalid credentials', code='invalid')]
            })
    def test_valid_data(self, login_mock):
        user = UserFactory(is_active=True)
        data = {
            'email': user.email,
            'password': USER_PASSWORD,
        }
        context = dict(request=RequestFactory())
        serializer = LoginSerializer(data=data, context=context)

        self.assertTrue(serializer.is_valid())
        self.assertEqual(serializer.save(), user)

        login_mock.assert_called_once_with(context['request'], user)
    def test_inactive_user(self):
        user = UserFactory(is_active=False)
        data = {
            'email': user.email,
            'password': USER_PASSWORD,
        }
        serializer = LoginSerializer(data=data)

        self.assertFalse(serializer.is_valid())
        self.assertDictEqual(
            serializer.errors, {
                'non_field_errors':
                [ErrorDetail(string='Invalid credentials', code='invalid')]
            })
예제 #9
0
 def post(self, request):
     form = LoginForm()
     serializer = LoginSerializer(data=request.data)
     if serializer.is_valid():
         print(serializer.data)
         user = authenticate(request,
                             username=serializer.data['username'],
                             password=serializer.data['password'])
         if user is not None:
             print("USERRRRRRRRRRRRRRR")
             login(request, user)
         print(request.data)
         return redirect('/home/')
     return Response({'form': form}, status=status.HTTP_200_OK)
    def test_invalid_data(self):
        data = {
            'email': 'email',
            'password': '******',
        }
        serializer = LoginSerializer(data=data)

        self.assertFalse(serializer.is_valid())
        self.assertDictEqual(
            serializer.errors, {
                'email': [
                    ErrorDetail(string='Enter a valid email address.',
                                code='invalid')
                ]
            })
예제 #11
0
파일: views.py 프로젝트: zyx852963/AuditSQL
    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            s, msg = serializer.authentication(request)
            if s:
                # 重定向到用户详情页面
                return HttpResponseRedirect(self.success_url)
            else:
                data = {'code': 2, 'data': msg}
                return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
        else:
            errors = [str(v[0]) for k, v in serializer.errors.items()]
            data = {'code': 2, 'data': '\n'.join(errors)}
            return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
예제 #12
0
def my_jwt_response_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': LoginSerializer(user, context={
            'request': request
        }).data
    }
예제 #13
0
    def post(self, request):
        # 反序列化验证数据
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取数据
        user = serializer.validated_data['user']

        # 将用户信息保存到session中
        request.session['user_id'] = user.id
        request.session['username'] = user.username
        request.session['mobile'] = user.mobile

        # 改最后一次登录时间
        user.last_login = datetime.now(tz=timezone.utc)
        user.save()

        return Response({'errno': RET.OK, 'errmsg': "登录成功"})
예제 #14
0
    def post(self, request, format='json'):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        email, pwd = serializer.data.values()

        try:
            user = User.objects.get(email=email)

            if user.check_password(pwd):
                token = self.get_token(user)
                return Response(self._get_login_payload(user, token), status.HTTP_200_OK)

        except User.DoesNotExist:
            pass

        raise AuthenticationFailed()
예제 #15
0
def LoginView(request, args=None):
    serializer = LoginSerializer(data=request.data)
    if serializer.is_valid():
        user = authenticate(username=serializer.validated_data['username'],
                            password=serializer.validated_data['password'])
        if user is not None:
            if user.is_active:
                login(request, user)
                response = {}
                response['username'] = serializer.validated_data['username']
                response['token'] = user.auth_token.key
                return Response(response, status=status.HTTP_200_OK)
            else:
                return Response(
                    {"error": "El usuario aun no ha sido activado. Revisa tu correo para activar la cuenta."},
                    status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({"error": "Password o usuario incorrectos."}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def test_missing_data(self):
        data = {
            'email': '',
            'password': '',
        }
        serializer = LoginSerializer(data=data)

        self.assertFalse(serializer.is_valid())
        self.assertDictEqual(
            serializer.errors,
            {
                'email': [
                    ErrorDetail(string='This field may not be blank.',
                                code='blank')
                ],
                'password': [
                    ErrorDetail(string='This field may not be blank.',
                                code='blank')
                ],
            },
        )
예제 #17
0
파일: api.py 프로젝트: skurt23/Welldone
    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            username = request.data.get('username')
            password = request.data.get('password')

            user = authenticate(username=username, password=password)
            if user is None:
                resp = {'success': False, 'message': "User not found"}
                return Response(resp, status=HTTP_400_BAD_REQUEST)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            resp = {'token': token, 'username': username, 'success': True}

            return Response(resp, status=HTTP_201_CREATED)
        else:
            resp = {'success': False, 'message': serializer.errors}
            return Response(resp, status=HTTP_400_BAD_REQUEST)
예제 #18
0
 def post(self, request):
     serializer = LoginSerializer(data=request.data)
     if serializer.is_valid(raise_exception=True):
         user = authenticate(email=serializer.data.get('email'),
                             password=serializer.data.get('password'))
         if user is not None:
             return Response(
                 {
                     "message": "Login Successful",
                     "data": {
                         "token":
                         Token.objects.get_or_create(user=user)[0].key
                     }
                 },
                 status=status.HTTP_200_OK)
         else:
             return Response(
                 {
                     "message": "Email or Password Incorrect",
                     "data": serializer.errors
                 },
                 status=status.HTTP_400_BAD_REQUEST)
예제 #19
0
 def login(self, request):
     serializer = LoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return Response(
         data=serializer.data,
         status=status.HTTP_200_OK
     )
예제 #20
0
 def create(self, request):
     serializer = LoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user, token = serializer.save()
     data = {'user': CustomUserSerializer(user).data, 'access_token': token}
     return Response(data, status=201)
예제 #21
0
 def _ok_response(self, user, csrftoken):
     response = Response(LoginSerializer(user).data)
     response.data['csrftoken'] = csrftoken
     return response