Beispiel #1
0
class LoginView(APIView):
    @swagger_auto_schema(
        operation_id='login_user',
        request_body=LoginSerializer,
        responses={
            '202': set_example(responses.login_202),
            '400': set_example(responses.login_400),
            '401': set_example(responses.login_401),
        },
    )
    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            user = authenticate(username=serializer.data['email'],
                                password=serializer.data['password'])

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

                return Response({'token': f"Token {token.key}"},
                                status.HTTP_202_ACCEPTED)
            else:
                return Response({'message': 'Credentials did not match'},
                                status.HTTP_401_UNAUTHORIZED)
        else:
            data = serializer.errors
            return Response(data, status.HTTP_400_BAD_REQUEST)
Beispiel #2
0
class MentorView(generics.ListAPIView):
    permission_classes = [
        AllowAny,
    ]
    queryset = Mentor.objects.all()
    serializer_class = MentorListSerializer

    @swagger_auto_schema(
        operation_id='get_mentors',
        responses={
            '200': set_example(responses.get_mentors_200),
            '404': set_example(responses.mentors_not_found_404),
        },
    )
    def get(self, request, year):
        try:
            queryset = Mentor.objects.filter(year=year, flag=True)
        except:
            return Response(responses.mentors_not_found_404,
                            status.HTTP_404_NOT_FOUND)
        else:
            serializer = MentorListSerializer(queryset, many=True)
            data = serializer.data
            return Response(
                {
                    "message": "Mentors Fetched successfully.",
                    "data": data
                }, status.HTTP_200_OK)
Beispiel #3
0
class RegistrationAPIView(APIView):
    permission_classes = (AllowAny, )
    serializer_class = RegistrationSerializer

    @swagger_auto_schema(
        operation_id='create_user',
        request_body=RegistrationSerializer,
        responses={
            '201': set_example({}),
            '400': set_example(responses.user_registration_400)
        },
    )
    def post(self, request):
        serializer = RegistrationSerializer(data=request.data)

        if serializer.is_valid():
            # Creating random OTP & saving it in user model.
            otp = str(randint(1000, 9999))
            user = serializer.save(otp)
            # Sending the OTP in a mail.
            send_email_otp(recipient_list=[user.email], otp=otp)
            return Response({}, status.HTTP_201_CREATED)
        else:
            data = serializer.errors
            return Response(data, status.HTTP_400_BAD_REQUEST)
Beispiel #4
0
class EventRegisterView(APIView):
    permission_classes = [IsAuthenticated]
    @swagger_auto_schema(
        operation_id="event_register",
        responses = {
            '201': set_example(responses.event_registration_201),
            '200':set_example(responses.user_already_registered_event_200),
            '404':set_example(responses.event_does_not_exist_404),
            '401':set_example(responses.user_unauthorized_401)
        }
    )
    def post(self,request,id):
        user = request.user
        eventregister = EventRegister()
        try:
            event = Event.objects.get(id=id)
        except:
            return Response(responses.event_does_not_exist_404, status.HTTP_404_NOT_FOUND)

        if user.verified:
            #Checking if user is already registered
            try:
                EventRegister.objects.get(user=user,event=event)
            except:
                #Registering the user if not registered
                eventregister.user = user
                eventregister.event = event
                eventregister.save()
                return Response(responses.event_registration_201,status.HTTP_201_CREATED)

            return Response(responses.user_already_registered_event_200,status.HTTP_200_OK)

        return Response(responses.user_unauthorized_401,status.HTTP_401_UNAUTHORIZED)
Beispiel #5
0
class AuthCheckView(APIView):
    permission_classes = [IsAuthenticated]
    @swagger_auto_schema(
        operation_id="check_auth",
        responses = {
            '200' : set_example(responses.user_authenticated_200),
            '401' : set_example(responses.user_unauthorized_401)
        }
    )
    def get(self,request):
        return Response(responses.user_authenticated_200,status.HTTP_200_OK)
class AuthCheckView(APIView):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_id='auth_check',
        responses={
            '200': set_example(responses.auth_check_200),
            '401': set_example(responses.unauthenticated_401),
        },
    )
    def get(self, request):
        return Response("You are authenticated")
Beispiel #7
0
class ForgetPasswordView(APIView):

    serializer_class = ForgetPasswordSerializer

    @swagger_auto_schema(
        operation_id='forget_password',
        request_body=ForgetPasswordSerializer,
        responses={
            '200': set_example(responses.forget_password_200),
            '400': set_example(responses.forget_password_400),
            '404': set_example(responses.forget_password_404),
        },
    )
    def post(self, request):
        """
        Forgot Password API where the email is posted and OTP is sent to the user.
        """

        serializer = ForgetPasswordSerializer(data=request.data)

        # Checking if the email entered is valid.
        if serializer.is_valid():
            valid_data = serializer.validated_data

            # Check if such a user exists.
            try:
                user = CustomUser.objects.get(email=valid_data['email'])
            except CustomUser.DoesNotExist:
                return Response(responses.forget_password_404,
                                status.HTTP_404_NOT_FOUND)
            else:
                #Generate OTP
                otp = str(randint(1000, 9999))

                #Update OTP
                user.otp = otp
                user.save()

                #Send OTP
                send_email_otp(recipient_list=[user.email], otp=otp)

                return Response(responses.forget_password_200,
                                status.HTTP_200_OK)

        # If the email entered was invalid or empty.
        else:
            data = serializer.errors
            return Response(data, status.HTTP_400_BAD_REQUEST)
Beispiel #8
0
class ChangePasswordView(APIView):

    serializer_class = ChangePasswordSerializer

    @swagger_auto_schema(
        operation_id='change_password',
        request_body=ChangePasswordSerializer,
        responses={
            '200': set_example(responses.change_password_200),
            '400': set_example(responses.change_password_400),
            '404': set_example(responses.change_password_404),
            '401': set_example(responses.change_password_401),
        },
    )
    def post(self, request):
        '''
        Change password API is where the email, otp and password is posted and password is changed
        '''

        serializer = ChangePasswordSerializer(data=request.data)

        #checking if entered data is valid
        if serializer.is_valid():
            valid_data = serializer.validated_data

            # Check if such a user exists.
            try:
                user = CustomUser.objects.get(email=valid_data['email'])
            except CustomUser.DoesNotExist:
                return Response(responses.change_password_404,
                                status.HTTP_404_NOT_FOUND)

            #Checking is vorrect otp is entered
            if valid_data['otp'] == user.otp:

                #Update Password
                user.set_password(valid_data['password'])
                user.save()
                return Response(responses.change_password_200,
                                status.HTTP_200_OK)
            return Response(responses.change_password_401,
                            status.HTTP_401_UNAUTHORIZED)

        data = serializer.errors
        return Response(data, status.HTTP_400_BAD_REQUEST)
Beispiel #9
0
class RegistrationView(APIView):
    @swagger_auto_schema(
        operation_id='create_user',
        request_body=RegistrationSerializer,
        responses={
            '201': set_example({}),
            '400': set_example(responses.user_registration_400)
        },
    )
    def post(self, request):
        serializer = RegistrationSerializer(data=request.data)

        if serializer.is_valid():
            user = serializer.save()
            return Response({}, status.HTTP_201_CREATED)
        else:
            data = serializer.errors
            return Response(data, status.HTTP_400_BAD_REQUEST)
Beispiel #10
0
class FeedbackView(APIView):
    @swagger_auto_schema(
        request_body=FeedbackSerializer,
        responses={
            '201' : set_example(responses.feedback_created_201),
            '400' : set_example(responses.feedback_invalid_400)
        }
    )
    def post(self,request):
        serializer = FeedbackSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(responses.feedback_created_201,status.HTTP_201_CREATED)
        
        error = serializer.errors
        error_msg = ""
        for err in error:
            error_msg += "Error in field: "+str(err)+"- "+str(error[err][0]) + " "
        return Response({"message" : error_msg},status.HTTP_400_BAD_REQUEST)
Beispiel #11
0
class LoginAPIView(APIView):
    serializer_class = LoginSerializer

    @swagger_auto_schema(
        operation_id='login_user',
        request_body=LoginSerializer,
        responses={
            '202': set_example(responses.login_202),
            '400': set_example(responses.login_400),
            '401': set_example(responses.login_401),
            '404': set_example(responses.login_404)
        },
    )
    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            # Authenticating the user.
            found_email = serializer.data['email']
            user = authenticate(username=serializer.data['email'],
                                password=serializer.data['password'])
            if user:
                # Assigning the user, a token if not already assigned and returning it.
                token, _ = Token.objects.get_or_create(user=user)
                return Response({'token': f"Token {token.key}"},
                                status.HTTP_202_ACCEPTED)
            else:
                # Trying to check if there exists a user with the email.
                try:
                    if CustomUser.objects.get(email=found_email):
                        return Response(
                            {'detail': 'Credentials did not match'},
                            status.HTTP_401_UNAUTHORIZED)

                except CustomUser.DoesNotExist:
                    return Response({"detail": "User not found"},
                                    status.HTTP_404_NOT_FOUND)
        else:
            # Returning errors in case the email is invalid or empty.
            data = serializer.errors
            return Response(data, status.HTTP_400_BAD_REQUEST)
Beispiel #12
0
class EventUnregisterView(APIView):
    permission_classes = [IsAuthenticated]
    @swagger_auto_schema(
        operation_id="eventunregister",
        responses={
            '200' : set_example(responses.event_registration_deleted_200),
            '401' : set_example(responses.user_unauthorized_401),
            '404' : set_example(responses.event_does_not_exist_404)
        }
    )
    def post(self, request, id):
        try:
            event = Event.objects.get(id=id)
        except:
            return Response(responses.event_does_not_exist_404,status.HTTP_404_NOT_FOUND) 
        else:
            try:
                reg = EventRegister.objects.get(user = request.user, event= event)  
            except:
                return Response(responses.event_not_registered_404,status.HTTP_404_NOT_FOUND)
            else:
                reg.delete()
                return Response(responses.event_registration_deleted_200,status.HTTP_200_OK)    
Beispiel #13
0
from rest_framework.decorators import api_view
from .models import Speaker
from .serializers import SpeakerSerializer
from django.http import JsonResponse
from utils.swagger import set_example
from drf_yasg.utils import swagger_auto_schema
from . import responses


@swagger_auto_schema(
    operation_id='get_speakers',
    method='get',
    responses={'200': set_example(responses.get_speakers_200)})
@api_view(['get'])
def get_speakers_list(request):
    speakers_objs = Speaker.objects.all()
    speakers = SpeakerSerializer(speakers_objs, many=True).data
    response = {"message": "Speakers Fetched Successfully", "data": speakers}
    return JsonResponse(response, safe=False)
Beispiel #14
0
    nearestHospital = None

    for hospital in hospitals:
        curr = geodesic((hospital.lat, hospital.lng), (lat, lng))
        if curr < distance:
            nearestHospital = hospital
            distance = curr

    return nearestHospital


@swagger_auto_schema(
    operation_id='APP>>>smart_route',
    request_body=RoutingSerializer,
    responses={
        401: set_example(responses.unauthenticated_401),
        200: set_example(responses.smart_route_200),
    },
    method='post'
)
@api_view(['post'])
@permission_classes([IsAuthenticated])
def SmartRouteView(request):
    """
        sample request 
        {
        "originLat": 11.215659,
        "originLng": 77.357261,
        "destination": "puluapatti, Tiruppur, Tamil Nadu"
        }
    """
Beispiel #15
0
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from drf_yasg.utils import swagger_auto_schema
from utils.swagger import set_example


# Create your views here.
@swagger_auto_schema(
    operation_id="test_authentication",
    method='get',
    responses={
        '200':
        set_example({"message": "You are authenticated user!"}),
        '401':
        set_example(
            {"detail": "Authentication credentials were not provided."})
    })
@api_view(['get'])
@permission_classes([IsAuthenticated])
def check_token_authentication(req):
    return Response({"message": "You are authenticated user!"},
                    status.HTTP_200_OK)
Beispiel #16
0
                user.save()
                return Response(responses.change_password_200,
                                status.HTTP_200_OK)
            return Response(responses.change_password_401,
                            status.HTTP_401_UNAUTHORIZED)

        data = serializer.errors
        return Response(data, status.HTTP_400_BAD_REQUEST)


@swagger_auto_schema(
    operation_id='verify_otp',
    request_body=VerifyOTPSerializer,
    method='post',
    responses={
        '200': set_example(responses.verify_otp_200),
        '400': set_example(responses.verify_otp_400),
        '401': set_example(responses.verify_otp_401),
    },
)
@api_view([
    'POST',
])
@permission_classes([IsAuthenticated])
def verify_otp(request):
    '''
    After Signup Login, Verify OTP using this API. 
    '''
    res_status = status.HTTP_400_BAD_REQUEST
    user = request.user
    req_data = request.data
Beispiel #17
0
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.contrib.auth.models import User
from drf_yasg.utils import swagger_auto_schema
from decouple import config
from utils.swagger import set_example
from profiles.models import Leaderboard
from profiles.responses import leaderboard_response_example_200


@swagger_auto_schema(
    operation_id='update pull requests status',
    method='post',
    responses={
        '200':
        set_example({'detail': 'Successfully updated leaderboard'}),
        '400':
        set_example(
            {"detail": "Sorry, there is some issue with the webhooks."}),
        '404':
        set_example({"detail": "Cannot retrieve the user."})
    },
)
@api_view(['post'])
def pull_request(request):
    """
    This API is to keep a track of the PR's opened and the \
    contribution by any user by any user. This is automatically \
    handled by webhooks in the git repos.
    """
    try: