コード例 #1
0
class Login(APIView):
    '''
    API endpoint that allows user to login
    '''
    permission_classes = (AllowAny, )
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("username",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
    ])

    def post(self, request):
        # print(self.schema["usernname"])
        username = request.data.get('username')
        password = request.data.get('password')
        if username is None or password is None:
            return Response(
                {'error': 'Please provide both username and password'},
                status=HTTP_400_BAD_REQUEST)
        user = authenticate(username=username, password=password)
        print(username, password)
        if not user:
            return Response({'error': 'Invalid Credentials'},
                            status=HTTP_404_NOT_FOUND)
        token, _ = Token.objects.get_or_create(user=user)
        return Response({'token': token.key}, status=200)
コード例 #2
0
class DumpFixtureAPIView(generics.CreateAPIView):
    permission_classes = (SuperuserRequiredPermission, )
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("app_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=10)),
        coreapi.Field("model_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=50)),
        coreapi.Field("filter_options",
                      required=False,
                      location="form",
                      schema=coreschema.Object()),
        coreapi.Field("file_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=50)),
    ])

    def post(self, request, *args, **kwargs):
        """
        Download model fixture
        """
        serializer = DumpFixtureSerializer(data=request.data)
        if not serializer.is_valid():
            return Response('Data is not valid')
        form_data = serializer.data
        file_name = form_data.pop('file_name')
        json_data = get_model_fixture_dump(**form_data)
        return download(json_data, file_name)
コード例 #3
0
def call_record_create_schema():
    return schemas.ManualSchema(fields=[
        coreapi.Field("type",
                      required=True,
                      location="form",
                      description="1 (start type) or 2 (end type)",
                      type="integer"),
        coreapi.Field("timestamp",
                      required=True,
                      location="form",
                      description="YYYY-mm-dd HH:MM:SS",
                      type="string"),
        coreapi.Field("call_id",
                      required=True,
                      location="form",
                      description="Id of the call",
                      type="integer"),
        coreapi.Field("source",
                      required=False,
                      location="form",
                      description="Phone number that initiated the call",
                      type="string"),
        coreapi.Field("destination",
                      required=False,
                      location="form",
                      description="Phone number that received the call",
                      type="string")
    ])
コード例 #4
0
ファイル: v1.py プロジェクト: zajacm/lexpredict-contraxsuite
 def coreapi_schema(self):
     if self.request.method == 'GET':
         fields = [
             coreapi.Field("name",
                           required=False,
                           location="query",
                           schema=coreschema.String(max_length=30)),
             coreapi.Field("name_contains",
                           required=False,
                           location="query",
                           schema=coreschema.String(max_length=30))
         ]
     elif self.request.method == 'POST':
         fields = [
             coreapi.Field("params",
                           required=True,
                           location="body",
                           schema=coreschema.Object())
         ]
     else:
         fields = [
             coreapi.Field("name",
                           required=True,
                           location="body",
                           schema=coreschema.String(max_length=30))
         ]
     return schemas.ManualSchema(fields=fields)
コード例 #5
0
ファイル: v1.py プロジェクト: zajacm/lexpredict-contraxsuite
 def coreapi_schema(self):
     fields = [
         coreapi.Field(
             "auth_token",
             required=True,
             location="form",
             schema=coreschema.String(max_length=40),
         )]
     return schemas.ManualSchema(fields=fields)
コード例 #6
0
def price_rule_create_schema():
    return schemas.ManualSchema(fields=[
        coreapi.Field("rule_type",
                      required=True,
                      location="form",
                      description="1 (standart rule) or 2 (reduced rule)",
                      type="integer"),
        coreapi.Field("fixed_charge"),
        coreapi.Field("call_charge"),
        coreapi.Field("start_period"),
        coreapi.Field("end_period")
    ])
コード例 #7
0
def get_record_schema():
    """
    Generates a ManualSchema for RecordCreate view
    """
    record_schema = schemas.ManualSchema(
        fields=[
            coreapi.Field(
                "call_id",
                required=True,
                location="form",
                schema=coreschema.String(
                    description='Unique for each call record pair'
                ),
            ),
            coreapi.Field(
                "type",
                required=True,
                location="form",
                schema=coreschema.String(
                    description='Indicate if it\'s a call start or end record'
                )
            ),
            coreapi.Field(
                "timestamp",
                required=True,
                location="form",
                schema=coreschema.String(
                    description='The timestamp of when the event occurred'
                )
            ),
            coreapi.Field(
                "source",
                required=False,
                location="form",
                schema=coreschema.String(
                    description='The subscriber phone number that originated '
                                'the call'
                )
            ),
            coreapi.Field(
                "destination",
                required=False,
                location="form",
                schema=coreschema.String(
                    description='The phone number receiving the call'
                )
            ),
        ],
        encoding="application/json",
    )

    return record_schema
コード例 #8
0
class RegisterUser(APIView):
    ''' 
    API endpoint that allows user to register a new user
    username: '******'
    first name: ' enter the first name '
    last name: ' enter the last name '
    password1: ' enter the password ' 
    password2: ' enter the password again ' 
    '''
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("username",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("first_name",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("last_name",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password1",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password2",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
    ])
    permission_classes = (AllowAny, )

    def post(self, request):
        username = request.data.get('username')
        first_name = request.data.get('first_name')
        last_name = request.data.get('last_name')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        if password1 == password2:
            # user.password = password1
            user = User.objects.create_user(username, None, password1)
            user.first_name = first_name
            user.last_name = last_name
            try:
                user.save()
                return Response('user created')
            except:
                return Response('User already exists')
        else:
            return Response('please check the password')
コード例 #9
0
 def schema(self):
     field_name = "params"
     location = "body"
     required = True
     schema = coreschema.String(max_length=30)
     if self.request.method == 'GET':
         field_name = "name"
         location = "query"
         required = False
     elif self.request.method == 'POST':
         schema = coreschema.Object()
     return schemas.ManualSchema(fields=[
         coreapi.Field(field_name,
                       required=required,
                       location=location,
                       schema=schema)
     ])
コード例 #10
0
def get_bill_schema():
    """
    Generates a ManualSchema for BillList view
    """
    bill_schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "subscriber",
            required=True,
            location="path",
            schema=coreschema.String(
                description='Subscriber telephone number'
            )
        ),
        coreapi.Field(
            "reference",
            required=False,
            location="query",
            schema=coreschema.String(
                description='The reference period (month/year) '
            )
        )
    ])

    return bill_schema
コード例 #11
0
class RestaurantCollection(APIView):

    schema = schemas.ManualSchema(fields=[
        coreapi.Field("user id",
                      required=True,
                      location="query",
                      schema=coreschema.Integer()),
        coreapi.Field("longitude",
                      required=True,
                      location="query",
                      schema=coreschema.String()),
        coreapi.Field("latitude",
                      required=True,
                      location="query",
                      schema=coreschema.String()),
        coreapi.Field("country",
                      required=False,
                      location="query",
                      schema=coreschema.Integer()),
        coreapi.Field("city",
                      required=False,
                      location="query",
                      schema=coreschema.String()),
        coreapi.Field("postcode",
                      required=False,
                      location="query",
                      schema=coreschema.String()),
        coreapi.Field("restaurant name",
                      required=False,
                      location="query",
                      schema=coreschema.String()),
    ])

    def get(self, request, *args, **kwargs):
        """
        Get a list of all Restaurants. Based on Geographic location (eg., 
        country, city, postal code, restaurant name), supports all Django 
        Search options (eg., 'in', 'isnull', 'icontains', 'istartswith',
        'iendswith'). returns all favorite user restaurant including remaining 
        restaurant based search and ensures that Restaurant not blacklisted
        by user.

        serializer: .serializers.RestaurantSerializer
        omit_serializer: false
        many: true

        parameters_strategy: merge
        omit_parameters:
        - path

        parameters:
        - name: userId, example: 1
          required: true
          type: int
        - name: longitude, example: -2.172841
          required: true
          type: str
        - name: latitude, example: 57.149453
          required: true
          type: str
        - name: country, example: "United States"
          required: false
          type: str
        - name: city, example: "Aberdeen"
          required: false
          type: str
        - name: restaurantName__istartswith, example: "Aug"
          required: false
          type: str
        - name: postcode__iendswith, example: "1XZ"
          required: false
          type: str

        :returns: filtered restaurant based user search
        :rtype: json

    """

        controller = RestaurantListController(data=request.GET,
                                              request=request)
        controller.is_valid()
        kw = controller.cleaned_data['search']

        if "country" in request.GET:
            kw['country__countryName__contains'] = request.GET['country']

        try:
            objs = Restaurant.objects.filter(deleted__isnull=True, **kw)
        except (ValueError, ValidationError):
            raise exceptions.Http400(error_code='Restaurant List Error',
                                     errors='check the search fields in parms')

        favorite = UserFavoriteRestaurant.objects.filter(
            deleted__isnull=True,
            user=request.GET['userId']).values_list('restaurant', flat=True)
        blocklist = UserBlocklistRestaurant.objects.filter(
            deleted__isnull=True,
            user=request.GET['userId']).values_list('restaurant', flat=True)
        favoriteList, restaurants = [], []
        for obj in objs:
            if obj.idRestaurant in favorite:
                data = status_distance(request, obj)
                obj.distance, obj.status = data[0], data[1]
                favoriteList.append(obj)
            else:
                if obj.idRestaurant not in blocklist:
                    data = status_distance(request, obj)
                    obj.distance, obj.status = data[0], data[1]
                    restaurants.append(obj)

        page = controller.cleaned_data['page']
        limit = controller.cleaned_data['limit']
        metadata = {
            'page': page,
            'limit': limit,
            'order': controller.cleaned_data.get('order'),
            'totalRecords': len(favoriteList + restaurants)
        }
        if controller.cleaned_data.get('order'):
            objs = objs.order_by(controller.cleaned_data['order'])
        objs = objs[page * limit:(page + 1) * limit]
        response = dict()
        response['content'] = {
            'favoriteRestaurants':
            RestaurantSerializer(instance=favoriteList, many=True).data,
            'restaurants':
            RestaurantSerializer(instance=restaurants, many=True).data
        }

        response['_metadata'] = metadata
        return Response(response)
コード例 #12
0
class LoginApiView(APIView):
    """
    post:
        API for Login/Sin In
    """

    # Parameter description for API documentation starts here
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "username",
            required=True,
            location="form",
            schema=coreschema.String(
                description=""
            )
        ),
        coreapi.Field(
            "password",
            required=True,
            location="form",
            schema=coreschema.String(
                description=""
            )
        ),

    ])

    # Parameter description for API documentation ends here

    def post(self, request):
        username = request.data.get('username', None)
        password = request.data.get('password', None)
        if re.match(r"[^@]+@[^@]+\.[^@]+", username):
            username = username.lower()
        if username and password:
            try:

                user = authenticate(username=username, password=password)
                if user and user.is_active and user.is_staff == False:
                    user.last_login = timezone.now()
                    user.save()

                    user_detail = {
                        'username': user.username,
                        'password': password
                    }
                    jwt_token = jwt_helper.get_my_token(user_detail)

                    return Response(
                        {
                            'status': status.HTTP_200_OK,
                            'message': 'You have been successfully logged in',
                            'data': {
                                'username': user.username,
                                'email': user.email,
                                'name': user.name,
                                'profile_pic': user.profile_pic
                            },
                            'token': jwt_token
                        },
                        status=status.HTTP_200_OK)
                else:
                    return Response(
                        {
                            'message': 'Invalid credentials.',
                            'data': {}
                        },
                        status=status.HTTP_401_UNAUTHORIZED)
            except Exception as e:
                print('********LOGIN EXCEPTION**********')
                print(str(e))
                return Response(
                    {
                        'message': 'Server error.',
                        'data': {}
                    },
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            return Response(
                {
                    'message': 'Email and Password are required fields',
                    'data': {}
                },
                status=status.HTTP_400_BAD_REQUEST)
コード例 #13
0
class SocialAuth(APIView):
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "access_token",
            required=True,
            location="form",
            schema=coreschema.String(
                description="access_token of user"
            )
        ),
        coreapi.Field(
            "email",
            required=True,
            location="form",
            schema=coreschema.String(
                description="email of user"
            )
        ),
        coreapi.Field(
            "auth_time",
            required=False,
            location="form",
            schema=coreschema.String(
                description="auth time from google auth"
            )
        ),
    ])

    def post(self, request, backend):
        token = request.data['access_token']
        email = request.data['email']
        auth_time = request.data['auth_time']
        try:
            user = User.objects.get(email=email)
            UserSocialAuth.objects.create(
                provider='google-oauth2', uid=email,
                extra_data={
                    "access_token": "token", "expires": None,
                    "auth_time": auth_time, "token_type": 'Bearer'
                },
                user_id=user.id)

        except:
            backend = GoogleOAuth2()
            try:
                backend.do_auth(token)
            except:
                return Response(
                    {
                        'status': status.HTTP_400_BAD_REQUEST,
                        'message': 'Login failed, login with login page or provide correct credentials'
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )
            user = backend.do_auth(token)
            if user.name:
                pass
            else:
                user.name = user.username
            user.username = email
            user.save()

            if not user:
                return Response(
                    {
                        'status': status.HTTP_400_BAD_REQUEST,
                        'message': 'login failed! ,login with login page or provide correct credentials'
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            try:
                UserProfile.objects.create(user=user)
            except:
                pass
        refresh = RefreshToken.for_user(user)
        if refresh:

            return Response(
                {
                    'status': status.HTTP_200_OK,
                    'message': 'user has been authenticated from google please find the jwt token',
                    'token': str(refresh.access_token)
                },
                status=status.HTTP_200_OK
            )
        else:
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'login failed login with login page or provide correct credentials'
                },
                status=status.HTTP_400_BAD_REQUEST
            )
コード例 #14
0
ファイル: views.py プロジェクト: mcbrandt13/kpbrandt
from .serializers import ApiWeatherSerializer
from .serializers import SimpleMsgSerializer
from .serializers import GenericSerializer
from .serializers import ApiWeatherResponseSerializer
from .serializers import QuotesSerializer
from . import models


@api_view(['GET'])
@schema(
    schemas.ManualSchema(fields=[
        coreapi.Field('city',
                      required=True,
                      location='query',
                      schema=coreschema.String(),
                      description='City'),
        coreapi.Field('state',
                      required=True,
                      location='query',
                      schema=coreschema.String(),
                      description='State')
    ]))
@parser_classes((JSONParser, ))
@permission_classes((AllowAny, ))
@renderer_classes((JSONRenderer, ))
def weather(request):
    """
    Get the forecast by providing city and state.
    """
    serializer = ApiWeatherSerializer(data=request.query_params)
    serializer.is_valid(raise_exception=True)
    key = settings.WEATHER_API_KEY
コード例 #15
0
class UpdateUserProfile(APIView):
    """
    put:
        API for update user profile data
    """
    # Parameter description for API documentation starts here
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "name",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Enter full name"
            )
        ),
        coreapi.Field(
            "mobile",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Enter Phone."
            )
        ),
        coreapi.Field(
            "email",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Enter email"
            )
        ),
        coreapi.Field(
            "biography",
            required=False,
            location="form",
            schema=coreschema.String(
                description="Enter biography"
            )
        ),
        coreapi.Field(
            "username",
            required=False,
            location="form",
            schema=coreschema.String(
                description="Enter username"
            )
        )
    ])

    # Parameter description for API documentation ends here

    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):

        try:
            user_profile = UserProfile.objects.get(user=request.user)
            user = User.objects.get(id=request.user.id)

        except ValidationError as v:
            return Response(
                {
                    'status': status.HTTP_401_UNAUTHORIZED,
                    'message': 'invalid token. profile not exist',
                    'data': ''
                }
            )
        name = request.data['name'] if request.data['name'] != '' else None
        email = request.data['email'] if request.data['email'] != '' else None
        phone = request.data['mobile'] if request.data['mobile'] != '' else None
        username = request.data['username'] if request.data['username'] != '' else None
        if phone == None or phone == '':
            return Response(
                {
                    'message': 'Phone number cannot be blank',
                    'status': status.HTTP_400_BAD_REQUEST
                },
                status=status.HTTP_400_BAD_REQUEST
            )
        if user.email != email:
            try:
                User.objects.get(email=str(email))
                return Response(
                    {
                        'message': 'Email already registered',
                        'status': status.HTTP_400_BAD_REQUEST
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )
            except:
                pass

        if user.mobile != phone:
            try:
                User.objects.get(mobile=phone)
                return Response(
                    {
                        'message': 'Phone already registered',
                        'status': status.HTTP_400_BAD_REQUEST
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )
            except:
                pass

        if user.username != username:
            try:
                User.objects.get(username=username)
                return Response(
                    {
                        'message': 'Username already registered',
                        'status': status.HTTP_400_BAD_REQUEST
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )
            except:
                pass
        if 'biography' in request.data:
            if request.data['biography'] == 'null':
                biography = None
            else:
                biography = request.data['biography']
        else:
            print('here3')
            biography = None
        if name and email and phone:

            if not phone.isdigit():
                return Response(
                    {
                        'message': 'Only digits has been taken as mobile number',
                        'status': status.HTTP_400_BAD_REQUEST
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            elif len(phone) != 10:
                return Response(
                    {
                        'message': 'Mobile number should be of 10 digits',
                        'status': status.HTTP_400_BAD_REQUEST
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
                return Response(
                    {
                        "status": status.HTTP_400_BAD_REQUEST,
                        "message": "invalid email id entered"
                    }, status=status.HTTP_400_BAD_REQUEST)

            user_profile.biography = biography
            user_profile.save()

            user.name = request.data['name']
            user.email = request.data['email']
            user.mobile = request.data['mobile']
            user.username = request.data['username']
            user.save()

            return Response(
                {
                    'status': status.HTTP_201_CREATED,
                    'message': 'Profile updated',
                    'data': user.username
                }, status=status.HTTP_201_CREATED
            )
        else:
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'All fields are required.'
                }, status=status.HTTP_400_BAD_REQUEST
            )
コード例 #16
0
class SocialUserCreateApiView(APIView):
    """
        post:
            API for Sign Up / Registration
        """

    # Parameter description for API documentation starts here
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "name",
            required=True,
            location="form",
            schema=coreschema.String(
                description="User's full name must be in valid alphabet with 3-40 characters long"
            )
        ),
        coreapi.Field(
            "username",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Choose a unique username"
            )
        ),
        coreapi.Field(
            "email",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Enter a valid email id"
            )
        ),
        coreapi.Field(
            "password",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Alphanumeric with minimum 8-15 characters"
            )
        ),
        coreapi.Field(
            "confirm_password",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Alphanumeric with minimum 8-15 characters"
            )
        ),

    ])

    # Parameter description for API documentation ends here

    def post(self, request):
        # print('++++++++++REQUESTED DATA FOR REG++++++++++++')
        # print(request.data)
        new_user = SocialUserCreateSerializer(data=request.data)
        if new_user.is_valid():
            try:
                new_user.validated_data['password'] = make_password(new_user.validated_data['password'])
                created_user = get_user_model().objects.create(**new_user.validated_data)
                created_user.create_profile()
                username = created_user.username
                password = request.data.get('password', None)
                if username and password:
                    try:

                        user = authenticate(username=username, password=password)
                        if user and user.is_active and user.is_staff == False:
                            user.last_login = timezone.now()
                            user.save()

                            user_detail = {
                                'username': user.username,
                                'password': password
                            }
                            jwt_token = jwt_helper.get_my_token(user_detail)

                    except Exception as e:
                        print('********LOGIN EXCEPTION**********')
                        print(str(e))
                        return Response(
                            {
                                'message': 'Server error.',
                                'data': {}
                            },
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

                return Response(
                    {
                        'status': status.HTTP_201_CREATED,
                        'message': 'You are successfully registered with us.',
                        'data': {
                            'username': created_user.username,
                            'email': created_user.email,
                            'name': created_user.name,
                            'token': jwt_token
                        }
                    },
                    status=status.HTTP_201_CREATED)

            except Exception as e:

                error_msg = ''
                for key, value in new_user.errors.items():
                    error = {'field': key, 'message': value}
                    error_msg = str(key) + ': ' + str(value[0]) + ' '
                return Response(
                    {
                        'message': error_msg
                    },
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        error_msg = ''
        for key, value in new_user.errors.items():
            error = {'field': key, 'message': value}
            error_msg = str(key) + ': ' + str(value[0]) + ' '

        return Response(
            {
                'status': status.HTTP_400_BAD_REQUEST,
                'message': error_msg
            }, status=status.HTTP_400_BAD_REQUEST)
コード例 #17
0
class UpdateProfilePic(APIView):
    """
    post:
        API for update user profile picture. Auth token required.
    """
    # Parameter description for API documentation starts here
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "profile_pic",
            required=False,
            location="form",
            schema=coreschema.Object(
                description="Test this API with Postmen"
            )
        )
    ])

    # Parameter description for API documentation ends here
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):

        try:
            user = User.objects.get(id=request.user.id)

        except ValidationError as v:
            return Response(
                {
                    'status': status.HTTP_401_UNAUTHORIZED,
                    'message': 'invalid token',
                    'data': ''
                }
            )

        if 'profile_pic' not in self.request.data:
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'Invalid file given',
                    'data': ''
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        file_name = self.request.data['profile_pic']
        if not file_name.name.lower().endswith(('.jpg', '.jpeg')):
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'Invalid image format is given',
                    'data': ''
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        rndm = random.randint(100000, 9999999)
        upload_dir = make_dir(
            settings.MEDIA_ROOT + settings.CUSTOM_DIRS.get('USER_IMAGE') + '/' + str(rndm) + '/'
        )

        file_name = file_upload_handler(file_name, upload_dir)

        profile_pic = settings.MEDIA_URL + settings.CUSTOM_DIRS.get('USER_IMAGE') + '/' + str(
            rndm) + '/' + file_name

        user.profile_pic = profile_pic
        user.save()

        return Response(
            {
                'status': status.HTTP_201_CREATED,
                'message': 'Profile picture updated.',
                'data': {
                    'profile_pic': profile_pic,
                    'user_name': user.username
                }
            },
            status=status.HTTP_201_CREATED
        )
コード例 #18
0
class ForgotPasswordApi(APIView):
    """
    post:
        API for send email for forgot password
    """

    schema = schemas.ManualSchema(
        fields=[
            coreapi.Field(
                'email',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter registered email here"
                )
            )
        ]
    )

    def post(self, request):
        data = request.data
        email = data.get("email", None)
        if not email:
            return Response(
                {
                    "statu": status.HTTP_400_BAD_REQUEST,
                    "message": "Email parameter is required"
                }, status=status.HTTP_400_BAD_REQUEST)

        import re

        if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
            return Response(
                {
                    "status": status.HTTP_400_BAD_REQUEST,
                    "message": "invalid email id entered"
                }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)
        except Exception:
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    "message": "User corresponding to this email id does not exist."
                }, status=status.HTTP_400_BAD_REQUEST)

        pwd_reset_token = str(get_unique_id(user.id)).replace("-", "")
        user.password_reset_token = pwd_reset_token

        user.save()

        # Send Email
        subject = 'Analytics Steps: Forgot password link!'
        body = forgot_pwd_email_content(user, pwd_reset_token, 'https://www.analyticssteps.com')
        received_user = user.email

        if send_auth_email(subject, body, received_user):
            return Response(
                {
                    "status": status.HTTP_200_OK,
                    "message": "Password reset link sent on your registered email id"
                }, status=status.HTTP_200_OK)

        return Response(
            {
                "status": status.HTTP_400_BAD_REQUEST,
                "message": "Can not send the password reset link on your registered email. Please contact the"
                           " administrator"
            }, status=status.HTTP_400_BAD_REQUEST)
コード例 #19
0
class ResetPasswordApi(APIView):
    """
    post:
        API for Reset password
    """
    # Parameter Schema start here
    schema = schemas.ManualSchema(
        fields=[
            coreapi.Field(
                'reset_token',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter password reset token here"
                )
            ),
            coreapi.Field(
                'password',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter new password here"
                )
            ),
            coreapi.Field(
                'confirm_password',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter confirm here"
                )
            )
        ]
    )

    # Parameter Schema ends here
    def post(self, request):
        data = request.data
        password_reset_token = data.get("reset_token", None)
        new_password = data.get("password", None)
        confirm_password = data.get("confirm_password", None)

        if not password_reset_token or not new_password or not confirm_password:
            return Response(
                {
                    "status": status.HTTP_400_BAD_REQUEST,
                    "message": "Password, confirm password and password reset token are required fields"
                }, status=status.HTTP_400_BAD_REQUEST)

        if new_password != confirm_password:
            return Response(
                {
                    "status": status.HTTP_400_BAD_REQUEST,
                    "message": "New password, confirm password must be same"
                }, status=status.HTTP_400_BAD_REQUEST)

        user = User.objects.filter(password_reset_token=password_reset_token)

        if len(user) == 0:
            return Response(
                {
                    "status": status.HTTP_400_BAD_REQUEST,
                    "message": "Invalid password reset token"
                }, status=status.HTTP_400_BAD_REQUEST)

        user = user[0]

        user.password = make_password(new_password)
        user.password_reset_token = None
        user.save()
        subject = 'Analytics Steps: Password Reset successfully!'
        body = reset_pwd_email_content(user)

        send_auth_email(subject, body, user.email)

        return Response(
            {"status": status.HTTP_200_OK, "message": "Password has been reset successfully. Please login to continue"
             }, status=status.HTTP_200_OK)
コード例 #20
0
from rest_framework import schemas
from rest_framework.compat import coreapi, coreschema

custom_schema = schemas.ManualSchema(
    fields=[
        coreapi.Field("id",
                      required=True,
                      location="path",
                      schema=coreschema.String(
                          title="ID",
                          description="Foobar ID.",
                      )),
        coreapi.Field("foobar",
                      location="query",
                      schema=coreschema.String(
                          title="Foobar",
                          description="Foobar?",
                      )),
    ],
    description="",
)
コード例 #21
0
class UserCreateApiView(APIView):
    """
        post:
            API for Sign Up / Registration
        """

    # Parameter description for API documentation starts here
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "name",
            required=True,
            location="form",
            schema=coreschema.String(
                description="User's full name must be in valid alphabet with 3-40 characters long"
            )
        ),
        coreapi.Field(
            "username",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Choose a unique username"
            )
        ),
        coreapi.Field(
            "email",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Enter a valid email id"
            )
        ),
        coreapi.Field(
            "mobile",
            required=True,
            location="form",
            schema=coreschema.String(
                description="must with country code separated with space. Ex: +12 1234567890"
            )
        ),
        coreapi.Field(
            "password",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Alphanumeric with minimum 8-15 characters"
            )
        ),
        coreapi.Field(
            "confirm_password",
            required=True,
            location="form",
            schema=coreschema.String(
                description="Alphanumeric with minimum 8-15 characters"
            )
        ),

    ])

    # Parameter description for API documentation ends here

    def post(self, request):

        new_user = UserCreateSerializer(data=request.data)
        if new_user.is_valid():
            try:
                new_user.validated_data['password'] = make_password(new_user.validated_data['password'])
                created_user = get_user_model().objects.create(**new_user.validated_data)
                created_user.create_profile()
                subject = 'Analytics Steps: Registration!'
                body = reg_email(created_user)
                received_user = created_user.email

                res = send_auth_email(subject, body, received_user)
                print(res)

                return Response(
                    {
                        'status': status.HTTP_201_CREATED,
                        'message': 'You are successfully registered with us.',
                        'data': {
                            'username': created_user.username,
                            'email': created_user.email,
                            'name': created_user.name
                        }
                    },
                    status=status.HTTP_201_CREATED)

            except Exception as e:

                error_msg = ''
                for key, value in new_user.errors.items():
                    error = {'field': key, 'message': value}
                    error_msg = str(key) + ': ' + str(value[0]) + ' '
                return Response(
                    {
                        'message': 'Server error.',
                        'error_message': error_msg
                    },
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        error_msg = ''
        for key, value in new_user.errors.items():
            error = {'field': key, 'message': value}
            if key == 'password':
                error_msg = str(key) + ':' + str(value[0]) + ' '
            else:
                error_msg = str(value[0]) + ' '

        return Response(
            {
                'status': status.HTTP_400_BAD_REQUEST,
                'message': error_msg
            }, status=status.HTTP_400_BAD_REQUEST)
コード例 #22
0
class UserChangePasswordApi(APIView):
    """
    post:
        API for change password. Token is required.
    """

    schema = schemas.ManualSchema(
        fields=[
            coreapi.Field(
                'old_password',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter Old Password"
                )
            ),
            coreapi.Field(
                'new_password',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter New Password"
                )
            ),
            coreapi.Field(
                'confirm_password',
                required=True,
                location="form",
                schema=coreschema.String(
                    description="Enter Confirm Password"
                )
            )
        ]
    )

    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        email = request.user.email

        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')
        confirm_password = request.data.get('confirm_password')

        if old_password and new_password and confirm_password:
            user = User.objects.get(email=email)
            if user.check_password(old_password):
                if new_password == confirm_password:
                    user.password = make_password(new_password)
                    user.save()
                    return Response(
                        {
                            'status': status.HTTP_200_OK,
                            'message': 'Password has been changed. Login again with the new password'
                        },
                        status=status.HTTP_200_OK)
                else:
                    return Response(
                        {
                            'status': status.HTTP_400_BAD_REQUEST,
                            'message': 'New password and Confirm password does not match'
                        }, status=status.HTTP_400_BAD_REQUEST)


            else:
                return Response(
                    {
                        'status': status.HTTP_400_BAD_REQUEST,
                        'message': 'Invalid old password'
                    }, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'Old password, new password and confirm password are required fields'
                }, status=status.HTTP_400_BAD_REQUEST)
コード例 #23
0
These Schema should be for FBV(Function Based Views) only as swagger UI
and django rest framework schemas do not fully support schemas for FBV
"""
from rest_framework import schemas
import coreapi
import coreschema


user_login_schema = schemas.ManualSchema(
    description="""
    **User Validation**: This API returns a user object once 
    authentication against a username and password.
    """,
    fields=[
        coreapi.Field(
            "username",
            required=True,
            location="form",
            schema=coreschema.String(),
            example="test_user",
        ),
        coreapi.Field(
            "password",
            required=True,
            location="form",
            schema=coreschema.String(),
            example="test_password",
        )
    ]
)