Exemple #1
0
    def delete(self, id):

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        # Validate user to perform CRUD action on a bucketlist
        bucketlist = Bucketlist.query.filter_by(list_id=id).first()

        # Check if bucketlist exists
        if not bucketlist:
            return {'Error': 'Bucketlist does not exist'}, 404

        if g.current_user != bucketlist.created_by:
            return {'Error': 'Unauthorised access'}, 401

        try:
            # Delete bucketlist items for bucketlist
            db.session.query(Bucketlist_Item).filter(
                Bucketlist_Item.list_id == id).delete()

            db.session.delete(bucketlist)
            db.session.commit()
            return {'Message': 'Bucketlist deleted successfully'}, 200

        except Exception as error:
            db.session.rollback()
            return {'Error': str(error)}, 400
Exemple #2
0
def validate_access(self, bucketlist_id, bucketlistitem_id=None):
    """
    Check if user has authorisation to perform CRUD on bucketlist item

    returns set,tuple: if error/warning else int (current_user)
    """

    # Validate token
    _token = request.headers.get("Authorization")
    g.current_user = verify_auth_token(_token)

    if not isinstance(g.current_user, int):
        return g.current_user

    # Validate user to perform CRUD action on a bucketlist
    bucketlist = Bucketlist.query.filter_by(list_id=bucketlist_id).first()

    # Check if bucketlist exists
    if not bucketlist:
        return {'Error': 'Bucketlist does not exist'}, 404

    if g.current_user != bucketlist.created_by:
        return {'Error': 'Unauthorised access'}, 401

    # Check if bucketlist item exists
    if bucketlistitem_id:
        items = Bucketlist_Item.query.filter_by(
            list_id=bucketlist_id, item_id=bucketlistitem_id).first()

        if not items:
            return {'Error': 'Bucketlist item does not exist'}, 404

    return g.current_user
Exemple #3
0
    def get(self, id):

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        user = db.session.query(User).get(g.current_user)

        # Validate user to perform CRUD action on a user
        if (g.current_user != id and user.admin is not True):
            return {'Error': 'Unauthorised access'}, 401

        # Fetch user from the DB
        users = User.query.filter_by(user_id=id).first()

        # Check is user exists
        if not users:
            return {'Error': 'User does not exist'}, 400

        response = user_schema.jsonify(users)
        response.status_code = 200
        return response
Exemple #4
0
    def delete(self, id):

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        user = db.session.query(User).get(g.current_user)

        # Validate user to perform CRUD action on a user
        if not user.admin:
            return {'Error': 'Unauthorised access'}, 401

        # Check if the user exists
        users = User.query.filter_by(user_id=id).first()

        if not users:
            return {'Error': 'User does not exist'}, 400

        _username = users.username

        try:
            # Delete bucketlist and bucketlist items for user
            bucketlists = Bucketlist.query.filter_by(created_by=id).all()

            for bucketlist in bucketlists:
                db.session.query(Bucketlist_Item).filter_by(
                    list_id=bucketlist.list_id).delete()

            db.session.query(Bucketlist).filter_by(created_by=id).delete()

            db.session.delete(users)
            db.session.commit()
            return {
                'Message': 'User {} deleted successfully'.format(_username)
            }, 200

        except Exception as error:
            db.session.rollback()
            return {'Error': str(error)}, 400
Exemple #5
0
    def get(self):
        """
        Returns a list of all bucketlists for a particular user
        """

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        bucketlists = Bucketlist.query.filter_by(
            created_by=g.current_user).all()

        if not bucketlists:
            return {
                'Warning': 'No bucketlists available for current user'
            }, 400

        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('q',
                                   type=str,
                                   location='args',
                                   help='Search bucketlist name')
        self.reqparse.add_argument('page',
                                   type=int,
                                   location='args',
                                   default=1,
                                   help='Page to start')
        self.reqparse.add_argument('limit',
                                   type=int,
                                   location='args',
                                   default=20,
                                   help='Results per page')

        args = self.reqparse.parse_args()
        _query = args['q']
        _page = args['page']
        _limit = args['limit']

        if _limit and _limit > 100:
            return {'Error': 'Maximum number of results is 100'}, 400

        if _query:
            _query = _query.strip()

            bucketlists = Bucketlist.query.filter(
                Bucketlist.created_by == g.current_user,
                Bucketlist.list_name.ilike('%' + _query + '%')).order_by(
                    Bucketlist.list_id).paginate(_page, _limit, False)

            if not bucketlists.items:
                return {
                    'Error': 'No bucketlists with the word {}'.format(_query)
                }, 404

        else:
            bucketlists = Bucketlist.query.filter(
                Bucketlist.created_by == g.current_user).order_by(
                    Bucketlist.list_id).paginate(_page, _limit, False)

            if not bucketlists.items:
                return {
                    'Error': 'No bucketlists available for current user'
                }, 404

        if bucketlists.has_prev:
            prev_page = request.url_root + 'bucketlist_api/v1.0/bucketlists' \
                + '?page=' + str(_page - 1) + '&limit=' + str(_limit)
        else:
            prev_page = 'None'

        if bucketlists.has_next:
            next_page = request.url_root + 'bucketlist_api/v1.0/bucketlists' \
                + '?page=' + str(_page + 1) + '&limit=' + str(_limit)
        else:
            next_page = 'None'

        result = bucketlists_schema.dump(list(bucketlists.items))
        pages = {
            'message': {
                'prev_page': prev_page,
                'next_page': next_page,
                'total_pages': bucketlists.pages
            },
            'bucketlists': result.data
        }

        response = json.dumps(pages, sort_keys=False)

        return Response(response, status=200, mimetype='text/json')
Exemple #6
0
    def post(self):
        """
        Add a new bucketlist

        Attributes:
        - list_name (required): A string representing the bucketlist's name
        - description (optional): A string representing the
                                    bucketlist's description
        - created_by (required): An foreign key from table User
                                    representing owner of bucketlist
        """

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        try:
            args = self.reqparse.parse_args()
            _bucketlist = args['bucketlist'].strip()
            _description = args['description']

            bucketlists = Bucketlist.query.filter(
                Bucketlist.created_by == g.current_user,
                Bucketlist.list_name.ilike(_bucketlist)).first()

            # Validate the bucketlist name
            if not _bucketlist:
                return {'Error': 'Bucketlist name is required'}, 400

            if _bucketlist.isdigit() or \
                    len(_bucketlist) < 5 \
                    or len(_bucketlist) > 20:

                return {
                    'Error': 'Invalid bucketlist name (5-20 characters)'
                }, 400

            if bucketlists:
                return {'Error': 'Bucketlist already exists'}, 409

            if _description:
                _description = _description.capitalize().strip()

            bucketlist = Bucketlist(
                list_name=_bucketlist.capitalize(),
                description=_description,
                created_by=g.current_user,
            )

            # Persist to DB
            db.session.add(bucketlist)
            db.session.commit()

            return {
                'Message': 'Bucketlist added successfully successfully'
            }, 201

        except Exception as error:
            db.rollback()
            return {'Error': str(error)}, 400
Exemple #7
0
    def put(self, id):

        args = self.reqparse.parse_args()

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        # Validate user to perform CRUD action on a bucketlist
        bucketlists = Bucketlist.query.filter_by(list_id=id).first()

        # Check if bucketlist exists
        if not bucketlists:
            return {'Error': 'Bucketlist does not exist'}, 404

        if g.current_user != bucketlists.created_by:
            return {'Error': 'Unauthorised access'}, 401

        _bucketlist = args['bucketlist']
        _description = args['description']
        _done = args['done']

        try:
            if _bucketlist:
                _bucketlist = _bucketlist.strip()

                if _bucketlist.isdigit() or \
                        len(_bucketlist) < 5 or \
                        len(_bucketlist) > 20:
                    return {
                        'Error': 'Invalid bucketlist name (5-20 characters)'
                    }, 400

                bucketlist = Bucketlist.query.filter(
                    Bucketlist.created_by == g.current_user,
                    Bucketlist.list_name.ilike(_bucketlist)).first()

                # Before updating, check if the bucketlist exists
                if bucketlist:
                    return {'Error': 'Bucketlist already exists'}, 400

                bucketlists.list_name = _bucketlist.capitalize()

            if _description:
                bucketlists.description = _description.capitalize().strip()

            if _done is not None and bool(_done):
                _done = _done.strip()
                # Check if bucketlist items are all done
                incomplete_items = Bucketlist_Item.query.filter(
                    Bucketlist_Item.list_id == id,
                    Bucketlist.is_completed.is_(False)).first()

                if incomplete_items:
                    return {
                        'Error': 'Bucketlist has incomplete items/activities'
                    }, 403

            bucketlists.is_completed = bool(_done)

            # Update date_modified
            bucketlists.date_modified = datetime.now().isoformat(
                sep=' ', timespec='minutes')

            # Commit changes
            db.session.commit()

            # Fetch updated record
            bucketlists = Bucketlist.query.filter_by(list_id=id).first()

            response = bucketlist_schema.jsonify(bucketlists)
            response.status_code = 200
            return response

        except Exception as error:
            db.session.rollback()
            return {'Error': str(error)}, 400
Exemple #8
0
    def get(self, id):

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        # Validate user to perform CRUD action on a bucketlist
        bucketlist = Bucketlist.query.filter_by(list_id=id).first()

        # Check if bucketlist exists
        if not bucketlist:
            return {'Error': 'Bucketlist does not exist'}, 404

        if g.current_user != bucketlist.created_by:
            return {'Error': 'Unauthorised access'}, 401

        try:
            items = Bucketlist_Item.query.join(
                Bucketlist,
                (Bucketlist_Item.list_id == Bucketlist.list_id)).filter(
                    Bucketlist.list_id == id).all()

            bucketlist_details = {
                'id': bucketlist.list_id,
                'name': bucketlist.list_name,
                'description': bucketlist.description,
                'items': ['No bucketlist items available'],
                'date_created': str(bucketlist.created_on),
                'date_modified': str(bucketlist.date_modified),
                'created_by': bucketlist.created_by,
                'done': bucketlist.is_completed,
            }

            item_details = []
            if items:
                for item in items:
                    item_details.append({
                        'id':
                        item.item_id,
                        'name':
                        item.item_name,
                        'date_created':
                        str(item.created_on),
                        'date_modified':
                        str(item.date_modified),
                        'done':
                        item.is_completed,
                    })

                bucketlist_details['items'] = item_details

            response = json.dumps(bucketlist_details, sort_keys=False)

            return Response(response, status=200, mimetype='text/json')

        except Exception as error:
            db.session.rollback()
            return {'Error': str(error)}, 400
Exemple #9
0
    def get(self):

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        user = db.session.query(User).get(g.current_user)

        if not user.admin:
            return {'Error': 'Unauthorised access'}, 401

        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('q',
                                   type=str,
                                   location='args',
                                   help='Search username')
        self.reqparse.add_argument('page',
                                   type=int,
                                   location='args',
                                   default=1,
                                   help='Page to start')
        self.reqparse.add_argument('limit',
                                   type=int,
                                   location='args',
                                   default=20,
                                   help='Results per page')

        args = self.reqparse.parse_args()
        _query = args['q']
        _page = args['page']
        _limit = args['limit']

        if _limit and _limit > 100:
            return {'Error': 'Maximum number of results is 100'}, 400

        if _query:
            users = User.query.filter(
                User.admin.isnot(True),
                User.username.contains('%' + _query + '%')).order_by(
                    User.username).paginate(_page, _limit, False)

            if not users.items:
                return {
                    'Error': 'No users with the name/word {}'.format(_query)
                }, 404

        else:
            users = User.query.filter(User.admin.isnot(True)).order_by(
                User.username).paginate(_page, _limit, False)

            if not users:
                return {'Warning': 'No users registered'}, 404

        if users.has_prev:
            prev_page = request.url_root + 'bucketlist_api/v1.0/users' \
                + '?page=' + str(_page - 1) + '&limit=' + str(_limit)
        else:
            prev_page = 'None'

        if users.has_next:
            next_page = request.url_root + 'bucketlist_api/v1.0/users' \
                + '?page=' + str(_page + 1) + '&limit=' + str(_limit)
        else:
            next_page = 'None'

        result = users_schema.dump(list(users.items))
        pages = {
            'message': {
                'prev_page': prev_page,
                'next_page': next_page,
                'total_pages': users.pages
            },
            'bucketlists': result.data
        }

        response = json.dumps(pages, sort_keys=False)

        return Response(response, status=200, mimetype='text/json')
Exemple #10
0
    def put(self, id):
        args = self.reqparse.parse_args()

        # Validate token
        _token = request.headers.get("Authorization")
        g.current_user = verify_auth_token(_token)

        if not isinstance(g.current_user, int):
            return g.current_user

        user = db.session.query(User).get(g.current_user)

        # Validate user to perform CRUD action on a user
        if g.current_user != id:
            return {'Error': 'Unauthorised access'}, 401

        if not user:
            return {'Error': 'User does not exist'}, 400

        _username = args['username']
        _userPassword = args['password']
        _active = args['active']

        try:
            if _username:
                _username = _username.strip()

                users = User.query.filter(
                    User.username.ilike(_username)).first()

                if users:
                    if users.username == _username:
                        return {'Error': 'Username not modified'}, 304

                    return {'Error': 'Username or email already exists'}, 409

                user.username = _username

            if _userPassword:
                _userPassword = _userPassword.strip()

                if (len(_userPassword) < 8 or len(_userPassword) > 15):
                    db.session.rollback()
                    return {
                        'Message': 'Password should have 8-15 characters'
                    }, 400

                user.password = _userPassword

            if _active:
                _active = _active.strip()
                user.active = bool(_active)

            db.session.commit()

            # Fetch updated record
            user = User.query.filter_by(user_id=id).first()

            response = user_schema.jsonify(user)
            response.status_code = 200
            return response

        except Exception as error:
            db.session.rollback()
            return {'Error': str(error)}, 400