Exemplo n.º 1
0
    def post(self, request, *args, **kwargs):
        """

        :param request:user request for create a note
        :return:this function is used for create new note and save

        """

        try:
            request_data = request.data
            if "collaborator" in request_data:
                collaborators = request_data['collaborator']
                result = NoteService().add_collaborator(collaborators)
                if not result['success']:
                    return HttpResponse(json.dumps(result))
                request_data['collaborator'] = result['data']
            if "label" in request_data:
                labels = request_data['label']
                label_result = NoteService().add_label(labels)
                if not label_result['success']:
                    return HttpResponse(json.dumps(label_result))
                request_data['label'] = label_result['data']
            serializer = NoteSerializers(data=request_data, partial=True)
            if serializer.is_valid():
                serializer.save(user=request.user)
                user = request.user
                update_redis(user)
                smd = Smd_Response(True, 'successfully note updated', data=[serializer.data], status_code=200)
                logger.info('successfully note updated')
            else:
                smd = Smd_Response(False, serializer.errors, [])
        except Exception as e:
            smd = Smd_Response()
            logger.error('something was wrong ' + str(e))
        return smd
Exemplo n.º 2
0
def access_token(request):
    """

    :param request: here we get code from google oauth2
    :return:in this function using the code from the google get access token by using that token we get user information
           after that we create that user and successfully logged in user
    """
    try:
        path = request.get_full_path()
        code_path = path.split('&')
        code = code_path[0].split('=')
        code = unquote(code[1])
        print(code)

        url = settings.GOOGLE_ACCESS_TOKEN_URI
        data = {
            "code": code,
            "client_id": settings.GOOGLE_OAUTH2_KEY,
            "client_secret": settings.GOOGLE_OAUTH2_SECRET,
            "grant_type": "authorization_code",
            "redirect_uri": settings.GOOGLE_REDIRECT_URI
        }
        response = requests.post(url, data)
        url = settings.GOOGLE_AUTH
        print(response.text)
        user_create = requests.post(url, response.json())
        print(user_create.status_code)
        if user_create.status_code == 201:
            return redirect(settings.BASE_URL)
        else:
            smd = Smd_Response(message='social user is not created')
    except Exception:
        smd = Smd_Response()
    return smd
Exemplo n.º 3
0
    def put(self, request, label_id, *args, **kwargs):
        """

        :param request: user request for put operation
        :param label_id: here we pass label_id  for specific update
        :return:this function used for update a label

        """
        try:
            user = request.user
            label = Label.objects.get(pk=int(label_id), user_id=user.id)
            if label:
                label.name = request.data['name']
                label.save()
                label_update_in_redis(user)
                smd = Smd_Response(True, 'label updated successfully', status_code=200)
                logger.info('label updated successfully')
            else:
                smd = Smd_Response(False, 'please enter valid label id or user id ')
        except Label.DoesNotExist:
            smd = Smd_Response(False, 'please enter valid label id or user id ')
            logger.error('label not exist for this label id error from Note.views')
        except ValueError as e:
            smd = Smd_Response(False, 'please enter label id in digits')
            logger.error('value error occurred ' + str(e))
        except Exception as e:
            logger.error('parent exception occurred' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 4
0
 def get(self, request):
     try:
         user = request.user
         redis.Del(user.id)
         smd = Smd_Response(True, 'safely logged out', [])
     except Exception:
         smd = Smd_Response()
     return smd
Exemplo n.º 5
0
    def post(self, request, *args, **kwargs):
        """

        :param request: here we get post request
        :return:this is users api view for user users after users its generate the token

        """
        try:
            if not "username" in request.data and not "password" in request.data:
                raise KeyError("username or password is missing")
            if not 'username' in request.data:
                raise KeyError('username is missing')
            if not 'password' in request.data:
                raise KeyError('password is missing')
            username = request.data["username"]
            password = request.data["password"]
            print(username)
            if username == "" and password == "":
                raise KeyError("username and password is not be blank ")
            if username == "":
                raise KeyError('username is required')
            if password == "":
                raise KeyError('password is required')
            user = authenticate(username=username, password=password)
            if user:
                payload = {
                    'username': username,
                    'password': password,
                }
                token = Jwt().login_token(payload)
                redis.Set(user.id, token)
                smd = {"success": True, "message": "successful", "data": token}
                logger.info(
                    'successfully logged in info from users.views.login_api')
                return HttpResponse(json.dumps(smd))
            else:
                logger.warning(
                    'not valid user warning from users.views.login_api')
                smd = Smd_Response(False, 'please provide valid credentials',
                                   [])
        except KeyError as error:
            print(error)
            logger.warning(
                'any one input field is blank warning from users.views.login_api'
            )
            logger.error('any one input field is blank' + str(error))
            smd = Smd_Response(False, str(error), [])
        except Exception as e:
            logger.error('something is wrong warning' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        """

        :purpose: in this function we register a new user via sending jwt token on email
        :param request: here we get post request
        :return:in this function we take user input for registration and sent mail to email id

        """

        try:
            # pdb.set_trace()
            serializer = UserSerializer(data=request.data)
            if serializer.is_valid():
                user = serializer.save()
                user.is_active = False
                user.save()
                if user:
                    payload = {
                        'username': self.request.data['username'],
                        'email': self.request.data['email'],
                    }
                    token = Jwt().register_token(payload)
                    long_url = reverse('activate', args=[token])
                    short_url = get_short_url(long_url)  # Url object
                    message = render_to_string(
                        'users/token.html', {
                            'name': user.username,
                            'domain': get_current_site(request).domain,
                            'url': short_url.short_id
                        })
                    recipient_list = [
                        self.request.data['email'],
                    ]
                    response = Smd_Response(
                        True,
                        'you registered successfully for activate your account please check '
                        'your email',
                        status_code=200)
                    email_event.emit("account_activate_event", message,
                                     recipient_list)
                    return response
                response = Smd_Response(False,
                                        'you are not validated try again', [])
                return response
            logger.warning(
                'not valid input warning from users.views.register_api')
            return Smd_Response(message=serializer.errors)
        except Exception as e:
            logger.warning('something was wrong ' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 7
0
    def get(self, request, search_note):
        """

        :param request: user request for search note
        :param search_note: here we passing parameter for search note
        :return: this function return searched notes using elasticsearch search engine

        """
        try:
            # pdb.set_trace()
            user = request.user
            notes = NoteDocument.search().query({
                "bool": {"must": {

                    "multi_match": {
                        "query": search_note,
                        "fields": ['label.name', 'title', 'note', 'reminder', 'color']
                    }
                },

                    "filter": {
                        "term": {
                            'user_id': user.id
                        }

                    }
                }
            })
            total_count = notes.count()
            print(total_count)
            if total_count != 0:
                searched_notes = notes.to_queryset()
                print(searched_notes)
                serializer = NotesSerializer(searched_notes, many=True)
                print(serializer.data)
                # print(value_count)
                # # # print(json.dumps(posts))
                # result = notes[0:total_count].execute()
                # all_notes = result.to_dict()
                smd = Smd_Response(True, 'successfully', serializer.data, 200)
                logger.info('successfully notes searched and returned')
            else:
                logger.warning('for this search note does not exist')
                smd = Smd_Response(message='for this search note does not exist')
        except Exception as e:
            logger.error('while searching a notes exception accrued' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 8
0
 def middleware(request):
     try:
         if re.match('^/api/', request.get_full_path()) and not re.match('^/api/token/', request.get_full_path()):
             bearer_token = request.META.get("HTTP_AUTHORIZATION", "")
             if bearer_token.startswith("Bearer"):
                 token = bearer_token.split(' ')
                 jwt.decode(token[1], settings.SECRET_KEY, algorithm="HS256")
             else:
                 response = Smd_Response(message='Bearer is missing in token')
                 return response
         return get_response(request)
     except DecodeError:
         response = Smd_Response(message='not valid token')
         return response
     except Exception:
         response = Smd_Response()
         return response
Exemplo n.º 9
0
 def wraper(request, *args, **kwargs):
     try:
         header = request.META['HTTP_AUTHORIZATION']
         token = header.split(' ')
         decoded = jwt.decode(token[1],
                              settings.SECRET_KEY,
                              algorithm="HS256")
         redis_token = redis.Get(decoded['user_id'])
         if redis_token is None:
             raise KeyError
         return function(request, *args, **kwargs)
     except DecodeError:
         smd = Smd_Response(
             message='invalid token redirected to users page')
     except KeyError:
         smd = Smd_Response(message='user_id is not inside redis')
     except Exception:
         smd = Smd_Response()
     return smd
Exemplo n.º 10
0
    def post(self, request, *args, **kwargs):
        """

        :param request:user request for create a note
        :return:this function is used for create new note and save

        """
        try:
            serializer = LabelSerializers(data=request.data)
            if serializer.is_valid():
                serializer.save(user=request.user)
                smd = Smd_Response(True, 'label successfully created', status_code=200)
                logger.info('successfully label created')
            else:
                smd = Smd_Response(False, serializer.errors)
                logger.warning('not valid input warning from Note.views')
        except Exception as e:
            smd = Smd_Response()
            logger.error('something was wrong ' + str(e))
        return smd
Exemplo n.º 11
0
    def __call__(self, request, *view_args, **kwargs):
        # Code to be executed for each request before
        # the view (and later middleware) are called
        # print(request.method)
        # print(request.user)
        # print(request)
        # print(request.get_full_path())
        try:
            if request.get_full_path() == "/api/note/" and request.method == 'POST' or request.path.startswith(
                    reverse('note', args=[str])) and request.method == 'PUT':
                if request.headers['Content-Type'].split(';')[0] == 'multipart/form-data':
                    request_data = request.POST
                else:
                    request_data = json.loads(request.body)
                if 'label' in request_data or 'collaborator' in request_data:
                    if len(request_data['label']) != 0:
                        label_list = []
                        for label in request_data['label']:
                            print(label)
                            new_label = Label.objects.get(name=label)
                            label_list.append(new_label)
                    if len(request_data['collaborator']) != 0:
                        collaborator_list = []
                        for collaborator in request_data['collaborator']:
                            new_collaborator = User.objects.get(email=collaborator)
                            collaborator_list.append(new_collaborator)
                        response = self.function(request, *view_args, **kwargs)
                    else:
                        response = self.function(request, *view_args, **kwargs)
                else:
                    response = self.function(request, *view_args, **kwargs)
            else:
                return self.function(request, *view_args, **kwargs)
        except Label.DoesNotExist:
            response = Smd_Response(message='your label is not  valid please add label and try')

        except User.DoesNotExist:
            response = Smd_Response(message='for this email id user is not exist')
        except Exception:
            response = Smd_Response(message='something is wrong when validating your label or collaborator')
        return response
Exemplo n.º 12
0
    def get(self, request, *args, **kwargs):
        """

        :param request:user request for get all labels
        :return: this function perform get operation of labels

        """
        try:
            user = request.user
            data = redis.Get(user.username + 'label')
            if data:
                labels = pickle.loads(data)
                serializer = LabelSerializers(labels, many=True)
                smd = Smd_Response(True, 'successfully', data=serializer.data, status_code=200)
                logger.info('all labels get successfully from redis')
                return smd
            label = Label.objects.filter(user_id=int(user.id))
            if label:
                serializer = LabelSerializers(label, many=True)
                all_label = pickle.dumps(label)
                redis.Set(user.username + 'label', all_label)
                smd = Smd_Response(True, 'successfully', data=serializer.data, status_code=200)
                logger.info('all label get from database')
            else:
                smd = Smd_Response(False, 'for this user label not exist')
        except Label.DoesNotExist:
            smd = Smd_Response(False, 'for this user id label not available please enter valid user_id')
            logger.error('for this user id label not exist error from Note.views.get_label')
        except ValueError as e:
            smd = Smd_Response(False, 'please enter user id in digits')
            logger.error('value error occurred while getting all labels' + str(e))
        except Exception as e:
            smd = Smd_Response()
            logger.error('parent exception occurred while getting all labels' + str(e))
        return smd
Exemplo n.º 13
0
    def get(self, request, *args, **kwargs):
        """
        :param request:user request for get all notes
        :return: this function perform get operation of notes

        """
        try:
            user = request.user
            note_data = redis.Get(user.username)
            if note_data:
                notes = pickle.loads(note_data)
                serializer = NotesSerializer(notes, many=True)
                smd = Smd_Response(True, 'successfully', data=serializer.data, status_code=200)
                logger.info('successfully get notes from redis')
                return smd
            all_notes = Note.objects.filter(user_id=int(user.id), is_trash=False, is_archive=False)
            if all_notes:
                serializer = NotesSerializer(all_notes, many=True)
                note = pickle.dumps(all_notes)
                redis.Set(user.username, note)
                smd = Smd_Response(True, 'successfully', data=serializer.data, status_code=200)
                logger.info('successfully get notes from database')
            else:
                smd = Smd_Response(False, 'please enter valid user id')
        except Note.DoesNotExist:
            smd = Smd_Response(False, 'please enter valid user for get a note')
            logger.error('note not exist for this note id ')
        except ValueError:
            smd = Smd_Response(False, 'please enter user_id in digits')
        except Exception as e:
            logger.error('exception occurred while getting all notes' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 14
0
 def post(self, request, *args, **kwargs):
     """
     :param request: here is post request por set password
     :return: in this function we take email from user and send toaken for verification
     """
     try:
         if not 'email' in request.data:
             raise KeyError('email is missing')
         email = request.data['email']
         print(email)
         if email == "":
             raise KeyError('email field not be blank')
         if not validate_email(email):
             raise ValueError
         user = User.objects.get(email=email)
         if user:
             payload = {
                 'username': user.username,
                 'email': user.email,
             }
             token = Jwt().register_token(payload)
             long_url = reverse('reset_password', args=[token])
             short_url = get_short_url(long_url)  # Url object
             message = render_to_string(
                 'users/email_template.html', {
                     'name': user.username,
                     'domain': get_current_site(request).domain,
                     'url': short_url.short_id
                 })
             recipient_list = [
                 user.email,
             ]
             email_event.emit("reset_password_event", message,
                              recipient_list)
             smd = Smd_Response(
                 True,
                 'you"re email is verified for reset password check you"re email',
                 status_code=200)
             return smd
         else:
             smd = Smd_Response(False,
                                'you are not valid user register first', [])
             logger.warning(
                 'not valid user warning from users.views.Reset_password_api'
             )
     except ObjectDoesNotExist as e:
         logger.warning('email not registered' + str(e))
         smd = Smd_Response(False, 'this email id not registered', [])
     except ValueError as e:
         smd = Smd_Response(False, 'please provide valid email address', [])
         logger.warning('not valid email address' + str(e))
     except KeyError as error:
         smd = Smd_Response(False, str(error), [])
         logger.warning('input is blank ' + str(error))
     except Exception as e:
         logger.warning('something is wrong ' + str(e))
         smd = Smd_Response()
     return smd
Exemplo n.º 15
0
    def delete(self, request, note_id, *args, **kwargs):
        """

        :param request: user request for delete note
        :param note_id:here we pass note id for specific delete
        :return:this function used for perform delete operation of note

        """
        try:
            Note.objects.get(pk=int(note_id)).delete()
            user = request.user
            update_redis(user)
            smd = Smd_Response(False, 'note deleted successfully', status_code=200)
            logger.info('note deleted successfully')
        except Note.DoesNotExist as e:
            logger.error('note does not exist for this note id error from Note.views' + str(e))
            smd = Smd_Response(False, 'please enter valid note_id')
        except ValueError as e:
            smd = Smd_Response(False, 'please enter note_id in digits' + str(e))
        except Exception as e:
            logger.error('parent exception occurred ' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 16
0
    def put(self, request, note_id, *args, **kwargs):
        """
        :param request: user request for put operation
        :param note_id: here we pass note id for specific update
        :return:this function used for update a note
        """

        try:
            # request_data = json.loads(request.body)
            request_data = request.data

            if "collaborator" in request_data:
                collaborators = request_data['collaborator']
                result = NoteService().add_collaborator(collaborators)
                if not result['success']:
                    return HttpResponse(json.dumps(result))
                request_data['collaborator'] = result['data']
            if "label" in request_data:
                labels = request_data['label']
                label_result = NoteService().add_label(labels)
                if not label_result['success']:
                    return HttpResponse(json.dumps(label_result))
                request_data['label'] = label_result['data']
            update_note = Note.objects.get(pk=int(note_id))
            serializer = NoteSerializerPut(instance=update_note, data=request_data, partial=True)
            if serializer.is_valid():
                serializer.save()
                user = request.user
                update_redis(user)
                smd = Smd_Response(True, 'successfully note updated', data=[serializer.data], status_code=200)
                logger.info('successfully note updated')
            else:
                smd = Smd_Response(False, serializer.errors)
        except Exception as e:
            smd = Smd_Response()
            logger.error('something was wrong ' + str(e))
        return smd
Exemplo n.º 17
0
    def delete(self, request, label_id, *args, **kwargs):
        """

        :param request: user request for delete label
        :param label_id:here we pass label id for specific delete
        :return:this function used for perform delete operation of label

        """
        try:
            Label.objects.get(pk=int(label_id)).delete()
            user = request.user
            label_update_in_redis(user)
            smd = Smd_Response(False, 'label deleted successfully', status_code=200)
            logger.info('label deleted successfully')
        except Label.DoesNotExist:
            logger.error('label not exist for this label id error from Note.views')
            smd = Smd_Response(False, 'please enter valid label_id ')
        except ValueError as e:
            logger.error('value error occurred' + str(e))
            smd = Smd_Response(False, 'please enter label id in digits ')
        except Exception as e:
            logger.error('parent exception occurred' + str(e))
            smd = Smd_Response()
        return smd
Exemplo n.º 18
0
    def get(self, request, *args, **kwargs):
        """

        :param request: user request for get archive notes
        :return:this function is used for return all archive notes

        """
        try:
            user = request.user
            data = NoteService().pin_notes(user)
            if data['success']:
                return HttpResponse(json.dumps(data, indent=1), status=200)
            else:
                return HttpResponse(json.dumps(data), status=400)
        except Exception:
            smd = Smd_Response()
            return smd
Exemplo n.º 19
0
    def get(self, request, *args, **kwargs):
        """

        :param request: user request for get all reminder notes
        :return: this function is used for return all reminder nits fired or upcoming

        """
        try:
            user = request.user
            print(request.user)
            data = NoteService().reminder_notes(user)
            if data['success']:
                return HttpResponse(json.dumps(data, indent=1), status=200)
            else:
                return HttpResponse(json.dumps(data), status=400)
        except Exception:
            smd = Smd_Response()
            return smd
Exemplo n.º 20
0
    def post(self, request, *args, **kwargs):
        """

        :param request:here we get post request with access token
        :return:this function use that access token and authenticate with backend and create a user
                and return response code 201 for created

        """
        try:
            provider = 'google-oauth2'
            authed_user = request.user if not request.user.is_anonymous else None

            strategy = load_strategy(request)

            backend = load_backend(strategy=strategy,
                                   name=provider,
                                   redirect_uri=None)

            if isinstance(backend, BaseOAuth1):

                token = {
                    'oauth_token': request.data['access_token'],
                    'oauth_token_secret': request.data['access_token_secret'],
                }
            elif isinstance(backend, BaseOAuth2):

                token = request.data['access_token']
            try:
                user = backend.do_auth(token, user=authed_user)
            except AuthAlreadyAssociated:

                return Response(
                    {"errors": "That social media account is already in use"},
                    status=status.HTTP_400_BAD_REQUEST)

            if user and user.is_active:
                return Response('logged in', status=status.HTTP_201_CREATED)
            else:
                return Response({"errors": "Error with social authentication"},
                                status=status.HTTP_400_BAD_REQUEST)
        except Exception:
            smd = Smd_Response()
            return smd
Exemplo n.º 21
0
def pagination(request):
    """

    :param request:user request for get pages
    :return:this function used for pagination means gives data after request of page

    """
    try:
        note_list = Note.objects.all()
        paginator = Paginator(note_list, 10)
        page = request.GET.get('page', 1)
        notes = paginator.page(page)
    except PageNotAnInteger:
        notes = paginator.page(1)
    except EmptyPage:
        notes = paginator.page(paginator.num_pages)
    except Exception:
        smd = Smd_Response()
        return smd
    return render(request, 'users/pagination.html', {'notes': notes})