Ejemplo n.º 1
0
    def delete(self, request, *args, **kwargs):
        """
        @apiVersion 1.0.0
        @api {DELETE} /auth Login
        @apiName Logout
        @apiGroup Auth
        @apiPermission Authenticated

        @apiSuccessExample {json} Success-Response:
            HTTP/1.1 200 OK
            {
                "status": 200,
                "success": true,
                "errors: [],
                "data": {}
            }
        """
        try:
            token_key = get_token_from_header(request)
            token = Token.objects.get(key=token_key)
            user = token.user
            token.delete()
            user_logged_out.send(sender=user.__class__,
                                 request=request,
                                 user=user)
        except Exception:
            raise exceptions.AuthenticationFailed(_('Invalid Token'))
        return Response()
Ejemplo n.º 2
0
 def country(self, request, *args, **kwargs):
     """
 Get country list
 """
     countries = Country.objects.all().order_by('name')
     serializer = CountrySerializer(countries, many=True)
     return Response(serializer.data)
Ejemplo n.º 3
0
    def create(self, request, *args, **kwargs):
        """
    @apiVersion 1.0.0
    @api {POST} /user
    @apiName Register
    @apiGroup User
    @apiPermission none

    @apiParam {string} email user's email
    @apiParam {string} password user's password
    @apiParam {string} first_name user's first name
    @apiParam {string} last_name user's last name
    @apiParam {object} profile
    @apiParam {object} majors

    @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
        {
            "status": 200,
            "success": true,
            "errors: [],
            "data": {}
        }
    """
        json_user = request.data['user']
        user = json.loads(json_user)

        serializer = self.get_serializer(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        headers = self.get_success_headers(serializer.data)
        data = serializer.data
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)
Ejemplo n.º 4
0
    def profile(self, request):
        """
    @api {GET} /user/profile

    @apiSuccessExample {json} Success-Response:
      HTTP/1.1 200 OK
        {
          "errors": [],
          "status": 200,
          "success": true,
          "data": {
            "id": 3,
            "email": "*****@*****.**",
            "first_name": "Dat",
            "last_name": "Nguyen",
            "profile": {
              "gender": 5,
              "major_intake": "Test",
              "phone_number": null,
              "state": "Ahihi",
              "country": "Test",
              "office": "Test",
              "job_title": "Test",
              "message": null,
              "name": "Dat Nguyen"
            }
            
          }
        }
    """
        user = request.user
        data = UserSerializer(instance=user).data
        return Response(data)
Ejemplo n.º 5
0
    def update(self, request, pk, *args, **kwargs):
        """
    @apiVersion 1.0.0
    @api {PUT} /user/:id
    @apiName Update
    @apiGroup User
    @apiPermission none

    @apiParam {Object} profile User's profile

    @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
          {
            "data": {
                "id": 15,
                "email": "*****@*****.**",
                "first_name": "Dat",
                "last_name": "Nguyen",
                "profile": {
                    "gender": 5,
                    "phone_number": "0905772919",
                    "city": 12737,
                    "country": 229,
                    "organization": "Vinagame",
                    "title": "Software Engineer",
                    "status": null,
                    "avatar": "",
                    "birthday": "1994-10-11",
                    "linkedin": null
                },
                "majors": [
                    {
                        "major": 1,
                        "intake": 2017,
                        "name": "Electrical Engineering and Information Technology",
                        "shorten": "EEIT",
                        "degree": {
                            "value": 1,
                            "display": "Bachelor"
                        }
                    }
                ]
            },
            "errors": [],
            "success": true
          }
    """
        if int(pk) != request.user.id:
            raise PermissionDenied()
        serializer = self.get_serializer(data=request.data,
                                         instance=request.user,
                                         partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
        return Response(serializer.data)
Ejemplo n.º 6
0
def exception_handler(exc, context):
    """
    Override to handle exception returning structured format
    """
    if isinstance(exc, Http404):
        msg = _("Not found.")
        errors = {CODE.NOT_FOUND: six.text_type(msg)}
        set_rollback()
        return Response(errors=errors, status=status.HTTP_404_NOT_FOUND)

    elif isinstance(exc, PermissionDenied):
        msg = _("Permission denied.")
        errors = {CODE.PERMISSION_DENIED: six.text_type(msg)}
        set_rollback()
        return Response(errors=errors, status=status.HTTP_403_FORBIDDEN)
    if isinstance(exc, exceptions.APIException):
        code = getattr(exc, 'code', None)
        headers = {}

        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, dict):
            errors = exc.detail
        else:
            if not code:
                errors = {
                    camel_to_snake_case(exc.__class__.__name__): exc.detail
                }
            else:
                errors = {
                    code: ' '.join(exc.detail)
                } if isinstance(exc.detail, list) else {
                    code: exc.detail
                }
        set_rollback()
        return Response(errors=errors, status=exc.status_code, headers=headers)

    return None
Ejemplo n.º 7
0
 def login_success(self, user):
     user_logged_in.send(sender=user.__class__,
                         request=self.request,
                         user=user)
     token = Token.objects.create(user=user)
     return Response({
         'token': token.key,
         'user': {
             'id': user.id,
             'email': user.email,
         }
     })
Ejemplo n.º 8
0
    def cities(self, request, country_id, *args, **kwargs):
        """
    Get city list using country ID
    """
        try:
            country = Country.objects.get(id=country_id)
        except Country.DoesNotExist:
            raise NotFound('Country not found.')

        cities = City.objects.filter(country=country).order_by('name')
        serializer = CitySerializer(cities, many=True)
        return Response(serializer.data)
Ejemplo n.º 9
0
    def request_otp(self, request, identify=None, *args, **kwargs):
        """
    @apiVersion 1.0.0
    @api {POST} /user/request_otp Require otp
    @apiDescription Request send otp via email sent to email
    @apiName Verify user
    @apiGroup User
    @apiPermission None

    @apiError ParseError 400
    @apiError NotFound 404
    @apiError Throttled 429

    @apiParam {string} type email

    @apiParamExample {json} Request-by-email
        {
            "email": "*****@*****.**",
        }

    @apiSuccessExample {json} Success-with-email:
        {
          "data" : {
              "otp" : "655343",
              "signature" : "107b40205eff8bec52b8982ca7c216ce"
          },
          "status" : 200,
          "errors" : [],
          "success" : true
        }
    """
        email = request.data.get('email', None)
        if not email:
            raise ParseError('Email is required to generate OTP.')
        try:
            user = User.objects.get(email=email)
            otp_instance = user.get_otp_instance()
        except User.DoesNotExist:
            raise NotFound('User not found.')

        try:
            otp, signature = generate_otp_from_instance(otp_instance)
        except LimitedException:
            raise_throttled(OTP_INTERVAL.OTP_REQUEST)

        return Response({
            'otp': otp,
            'signature': signature,
        })
Ejemplo n.º 10
0
 def retrieve(self, request, pk=None, *args, **kwargs):
     """
 @apiVersion 1.0.0
 @api {GET} /user/:id User > Retrieve
 @apiDescription Retrieve User
 @apiGroup User
 @apiPermission Authenticated
 """
     if not request.user.is_authenticated:
         raise NotAuthenticated()
     try:
         instance = self.get_queryset().get(pk=pk)
     except Exception:
         raise NotFound()
     serializer = self.get_serializer(instance)
     return Response(serializer.data)
Ejemplo n.º 11
0
    def verify(self, request, *args, **kwargs):
        """
    @apiVersion 1.0.0
    @api {POST} /user/verify Verify OTP
    @apiDescription Verify given OTP with given signature
    @apiName Verify user
    @apiGroup User
    @apiPermission None

    @apiError ParseError 400
    @apiError NotFound 404
    @apiError Throttled 429

    @apiParam {string} type email

    @apiParamExample {json}
        {
            "signature": "107b40205eff8bec52b8982ca7c216ce",
            "otp": "655343"
        }

    @apiSuccessExample {json} Success-with-email:
        {
          "data" : {
              "otp" : "655343",
              "signature" : "107b40205eff8bec52b8982ca7c216ce"
          },
          "status" : 200,
          "errors" : [],
          "success" : true
        }
    """
        otp = request.data.get('otp', None)
        signature = request.data.get('signature', None)
        try:
            otp_instance = OneTimePassword.objects.get(signature=signature)
        except OneTimePassword.DoesNotExist:
            raise NotFound('User doesn\'t exist.')

        try:
            is_valid = is_valid_otp(otp, otp_instance)
        except LimitedException:
            raise_throttled(OTP_INTERVAL.OTP_CHECK)

        return Response({'valid': is_valid})
Ejemplo n.º 12
0
    def password(self, request, *args, **kwargs):
        otp = request.data.get('otp', None)
        data = request.data.copy()

        if otp is not None:
            serializer = UserChangePasswordByOTPSerializer(data=data)
            try:
                serializer.is_valid(raise_exception=True)
            except LimitedException:
                raise_throttled(OTP_INTERVAL.OTP_CHECK)
        else:
            if not request.user.is_authenticated:
                raise NotAuthenticated()
            context = dict(user=request.user)
            serializer = UserChangePasswordSerializer(data=data,
                                                      context=context)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({})
Ejemplo n.º 13
0
 def get_paginated_response(self, data):
     return Response(
         OrderedDict([('count', self.page.paginator.count),
                      ('num_pages', self.page.paginator.num_pages),
                      ('results', data), ('current', self.page.number)]))
Ejemplo n.º 14
0
 def major(self, request, *args, **kwargs):
     majors = Major.objects.all().order_by('degree')
     serializer = MajorSerializer(majors, many=True)
     return Response(serializer.data)