Beispiel #1
0
def login(data):
    data = _normalise_login_data(data)
    serializer = LoginSerializer(data=data)

    try:
        if serializer.is_valid():
            email = serializer.validated_data["email"]
            apple_id = serializer.validated_data["appleId"]
            token = serializer.validated_data["token"]
            auth_provider = serializer.validated_data["authProvider"]

            if auth_provider == "APPLE":
                email = get_email_for_apple_user(email, apple_id)
                if email is None:
                    return (
                        InvalidAppleUser(email=email,
                                         apple_id=apple_id).to_dict(),
                        status.HTTP_403_FORBIDDEN,
                    )

            response, response_status = check_registration({"email": email})

            if response_status == status.HTTP_204_NO_CONTENT:
                return (
                    UserNotRegistered(email=email).to_dict(),
                    status.HTTP_403_FORBIDDEN,
                )

            if not response.get("isApproved", False):
                return (
                    AccountNotApproved(email=email).to_dict(),
                    status.HTTP_403_FORBIDDEN,
                )

            if not check_profile_exists(email=email):
                return (
                    ProfileDoesNotExist(email=email).to_dict(),
                    status.HTTP_403_FORBIDDEN,
                )

            response, response_status = _login_valid_user(
                email, token, auth_provider)
        else:
            response, response_status = _form_bad_request_response(
                serializer.errors)

        return response, response_status
    except exceptions.AuthenticationFailed as e:
        response_status = e.status_code
        response = {"type": "failure", "message": e.detail}
        return response, response_status
    except ValueError as error:
        response_status = status.HTTP_401_UNAUTHORIZED
        response = {
            "type": "failure",
            "message": "Login failed.",
            "details": str(error),
        }
        return response, response_status
Beispiel #2
0
    def setUp(self):
        self.user = UserFactory()
        self.user.set_password('password')
        self.user.save()

        self.serializer_instance = LoginSerializer(data={
            'email': self.user.email,
            'password': '******'
        })
    def login(self, request):
        login_serializer = LoginSerializer(data=request.data)
        login_serializer.is_valid(raise_exception=True)

        user = login_serializer.validated_data['user']

        auth_token_serializer = AuthTokenSerializer(data={}, partial=True)
        auth_token_serializer.is_valid(raise_exception=True)
        auth_token_serializer.save(user=user)
        return Response(auth_token_serializer.data)
Beispiel #4
0
    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        try:
            u = User.objects.get(email=serializer.validated_data.get('email'))
            login(request, u)
            return Response(u.email)
        except:
            return Response({'email': 'email err'})
Beispiel #5
0
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = authenticate(email=serializer.data["email"],
                            password=serializer.data["password"])
        if user:
            return Response({
                "id": user.id,
                "email": user.email,
                "first_name": user.first_name,
                "last_name": user.last_name,
                "token": user.auth_token.key,
            })
        else:
            raise AuthenticationFailed
Beispiel #6
0
    def patch(request, profile_id):
        profile = get_object_or_404(Profile, pk=profile_id)

        if profile.user != request.user:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        serializer = ProfileSerializerUpdate(profile, data=request.data, context={'request': request}, partial=True)
        if serializer.is_valid():
            profile = serializer.save()
            return Response(LoginSerializer(profile.user).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #7
0
class LoginSerializerTestSuite(APITestCase):
    def setUp(self):
        self.user = UserFactory()
        self.user.set_password('password')
        self.user.save()

        self.serializer_instance = LoginSerializer(data={
            'email': self.user.email,
            'password': '******'
        })

    def test_login_user_is_valid_not_called(self):
        self.assertRaises(Exception, self.serializer_instance.login_user)

    def test_login_serializer_is_valid_called(self):
        self.serializer_instance.context['request'] = MagicMock()
        self.serializer_instance.is_valid()
        try:
            self.serializer_instance.login_user()
        except:
            self.fail('`.login_user()` raised an exception')
Beispiel #8
0
 def post(self, request):
     serializer = LoginSerializer(data=request.data)
     if serializer.is_valid():
         username = request.data.get('username', '')
         password = request.data.get('password', '')
         user = auth.authenticate(username=username, password=password)
         if user:
             auth_token = jwt.encode(
                 {
                     'username': user.username,
                     'create_date':
                     datetime.now().strftime(default_date_format)
                 }, settings.JWT_SECRET_KEY)
             data = {'user': serializer.data, 'token': auth_token}
             return Response(data, status=status.HTTP_200_OK)
         else:
             return Response({'detail': 'Invalid credentials'},
                             status=status.HTTP_401_UNAUTHORIZED)
     else:
         return Response({'Message': 'Bad Request'},
                         status=status.HTTP_400_BAD_REQUEST)
Beispiel #9
0
    def post(self, request):
        data = request.data
        username = data.get('email', '')
        password = data.get('password', '')
        print(username)
        print(password)

        user = auth.authenticate(username=username, password=password)
        print(user)

        if user:
            serializer = LoginSerializer(user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response({'message': 'Invalid Credentials try again'},
                        status=status.HTTP_401_UNAUTHORIZED)
Beispiel #10
0
    def post(self, request, format=None):

        request.data['email'] = request.data['email'].lower()

        request.data['username'] = request.data['email']

        if 'offset' not in request.data.keys():
            request.data['offset'] = 0

        if CustomUser.objects.filter(email=request.data['email']).exists():
            return Response(
                {
                    'status': 'Account Exists',
                    'message': 'An account with this email already exists.'
                },
                status=status.HTTP_400_BAD_REQUEST)

        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            customuser = CustomUser.objects.create_user(
                **serializer.validated_data)

            complete_signup.delay(customuser.pk)

            token = Token.objects.get(user=customuser)

            key = base64.b64encode(customuser.key.encode()).decode()
            md5 = base64.b64encode(
                hashlib.md5(customuser.key.encode()).digest()).decode()
            data = {
                'token': token.key,
                'key': key,
                'md5': md5,
                'categories': customuser.category_set.all(),
                'tracking': customuser.tracking_on
            }

            send = LoginSerializer(data)

            return Response(send.data)

        return Response(
            {
                'status': 'Bad request',
                'message': 'Account could not be created with received data.'
            },
            status=status.HTTP_400_BAD_REQUEST)
Beispiel #11
0
    def post(self, request, format=None):

        email = request.data['email'].lower()
        password = request.data['password']

        customuser = authenticate(email=email, password=password)

        if customuser is not None:
            if customuser.is_active:
                login(request, customuser)

                if 'offset' in request.data.keys():
                    customuser.offset = request.data['offset']
                    customuser.save()

                token = Token.objects.get(user=customuser)
                key = base64.b64encode(customuser.key.encode()).decode()
                md5 = base64.b64encode(
                    hashlib.md5(customuser.key.encode()).digest()).decode()
                data = {
                    'token': token.key,
                    'key': key,
                    'md5': md5,
                    'categories': customuser.category_set.all(),
                    'tracking': customuser.tracking_on
                }

                send = LoginSerializer(data)

                return Response(send.data)
            else:
                return Response(
                    {
                        'status': 'Unauthorized',
                        'message': 'This account has been disabled.'
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Username/password combination invalid.'
                },
                status=status.HTTP_401_UNAUTHORIZED)
Beispiel #12
0
def login(request: Request) -> Response:
    serializer = LoginSerializer(data=request.data,
                                 context={'request': request})
    serializer.is_valid(raise_exception=True)
    serializer.login_user()
    return Response(status=200, data={'Logged in successfully'})
Beispiel #13
0
 def get(self, request):
     serializer = LoginSerializer()
     return Response(serializer.data)
Beispiel #14
0
class AuthViewSet(viewsets.GenericViewSet):
    """
    Authentication ViewSet class
    """

    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: UserSerializer(),
        },
    )
    @action(
        methods=("POST",),
        detail=False,
        permission_classes=(permissions.IsAuthenticated,),
        serializer_class=EmptySerializer,
        pagination_class=None,
    )
    def user(self, request):
        """
        Retrieve basic data of current user
        """
        user_serializer = UserSerializer(request.user)

        return Response(
            data=user_serializer.data,
            status=status.HTTP_200_OK,
        )

    @swagger_auto_schema(
        request_body=LoginSerializer,
        responses={
            status.HTTP_200_OK: LoginSerializer(),
        },
    )
    @action(
        methods=("POST",),
        detail=False,
        permission_classes=(permissions.AllowAny,),
        serializer_class=LoginSerializer,
    )
    def login(self, request):
        """
        Endpoint which check username and password
        If these params are right and username exists in database
        and password is correct for the username than
        we will login user to the system
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = authenticate(
            username=serializer.validated_data["username"],
            password=serializer.validated_data["password"],
        )
        if user is None:
            raise serializers.ValidationError(
                "Invalid username/password. Please try again!"
            )
        user_serializer = UserSerializer(user)

        return Response(data=user_serializer.data, status=status.HTTP_200_OK)

    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: SuccessSerializer(),
        },
    )
    @action(
        methods=("POST",),
        detail=False,
        permission_classes=(permissions.AllowAny,),
        serializer_class=EmptySerializer,
        pagination_class=None,
    )
    def logout(self, request):
        """
        Calls Django logout method;
        Does not work for UserTokenAuth.
        """
        logout(request)

        success_serializer = SuccessSerializer(
            instance={
                "success": "Successfully logged out",
            }
        )
        return Response(
            data=success_serializer.data,
            status=status.HTTP_200_OK,
        )

    @swagger_auto_schema(
        request_body=PasswordChangeSerializer,
        responses={
            status.HTTP_204_NO_CONTENT: EmptySerializer(),
        },
    )
    @action(
        methods=["POST"],
        detail=False,
        permission_classes=(permissions.IsAuthenticated,),
        serializer_class=PasswordChangeSerializer,
    )
    def password_change(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        request.user.set_password(serializer.validated_data["new_password"])
        request.user.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @swagger_auto_schema(
        request_body=UserRegisterSerializer,
        responses={
            status.HTTP_200_OK: UserRegisterSerializer(),
        },
    )
    @action(
        methods=("POST",),
        detail=False,
        permission_classes=(permissions.AllowAny,),
        serializer_class=UserRegisterSerializer,
    )
    def register(self, request):
        """
        Register user with email, name and password data
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        activate_url = None
        if serializer.validated_data.get("activate_url"):
            activate_url = serializer.validated_data.pop("activate_url")

        user = get_user_model().objects.create_user(
            **serializer.validated_data,
            is_active=False,
        )
        user_serializer = UserSerializer(user)

        params = {
            "user_id_b64": urlsafe_base64_encode(force_bytes(user.pk)),
            "token": default_token_generator.make_token(user=user),
        }

        if activate_url:
            url_parts = list(urlparse(activate_url))
            query = dict(parse_qsl(url_parts[4]))
            query.update(params)
            url_parts[4] = urlencode(query)
            activate_url = urlunparse(url_parts)
        else:
            url_parts = urlparse(request.build_absolute_uri())
            parse_result = ParseResult(
                scheme=url_parts.scheme,
                netloc=url_parts.hostname,
                path=reverse(
                    "authentication:auth-activate",
                    kwargs=params,
                ),
                params=url_parts.params,
                query=None,
                fragment=url_parts.fragment,
            )
            activate_url = parse_result.geturl()

        send_activation_email(
            recipient_list=[user.email],
            activate_url=activate_url,
        )
        return Response(
            data=user_serializer.data,
            status=status.HTTP_201_CREATED,
        )

    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: UserSerializer(),
        }
    )
    @action(
        methods=("GET",),
        detail=False,
        permission_classes=(permissions.AllowAny,),
        serializer_class=UserRegisterSerializer,
        url_path=r"activate/(?P<user_id_b64>[\d\w-]+)/(?P<token>[\d\w-]+)",
        pagination_class=None,
    )
    def activate(self, request, user_id_b64, token):
        """
        Activate registered user account
        """
        try:
            uid = force_str(urlsafe_base64_decode(user_id_b64))
            user = User.objects.get(pk=uid)
        except (
            TypeError,
            ValueError,
            OverflowError,
            User.DoesNotExist,
        ):
            user = None

        if user and default_token_generator.check_token(user, token):
            user.is_active = True
            user.save()

            token, _ = Token.objects.get_or_create(user=user)

            message, status_code = {
                "success": "Successfully activated account",
                "token": token.key,
            }, status.HTTP_200_OK
        else:
            message, status_code = {
                "error": "Activation failed"
            }, status.HTTP_400_BAD_REQUEST

        return Response(data=message, status=status_code)
Beispiel #15
0
 def change_password(self, request, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid('raise_exceptions')
     serializer.save()
     return response.Response(LoginSerializer(request.user).data)