Ejemplo n.º 1
0
    def get(self, bucketlist_id, item_id=None):
        """
        Returns a bucketlist item

        Args:
            bucketlist_id -- the bucketlist identifier
            item_id :the bucketlist item identifier
        Returns:
            BucketList item query
        """
        if item_id:
            user_id = g.user.id
            bucket_item = Item.query.filter_by(bucketlist_id=bucketlist_id,
                                               item_id=item_id).first()
            if not bucket_item:
                return errors.not_found("No items found")
            return marshal(bucket_item, bucketlist_item_field), 200
        elif bucketlist_id:
            bucket_item = Item.query.filter_by(
                bucketlist_id=bucketlist_id).all()
            if not bucket_item:
                return errors.not_found("No items found for this bucketlist")
            return marshal(bucket_item, bucketlist_item_field), 200
        else:
            item = Item.query.filter().all()
            if item:
                return marshal(item, bucketlist_item_field), 200
            return errors.not_found('No items created')
Ejemplo n.º 2
0
    def put(self, bucketlist_id, item_id):
        """
        Edit the name of a bucketlist itrem

        Args:
            id :the bucketlist item  identiier
        Returns:
            a dictionary of the bucketlist  item updated
        """
        args = self.reqparse.parse_args()
        bucketlist = Bucketlist.query.filter_by(id=bucketlist_id,
                                                created_by=g.user.id).first()
        bucketlist_item = Item.query.filter_by(item_id=item_id).first()
        name = args['name']
        done = args['done']

        if not bucketlist:
            return errors.not_found('Invalid bucketlist id')
        if not bucketlist_item:
            return errors.not_found('Invalid item id')

        elif bucketlist_item:
            if done in [True, False]:
                bucketlist_item.done = done
            if name == bucketlist_item.name:
                return ({'message': 'Cannot update with same name.'}, 409)
            if name:
                bucketlist_item.name = name

            db.session.commit()
            return marshal(bucketlist_item, bucketlist_item_field), 200
Ejemplo n.º 3
0
def add_role_to_user(item_id, role_name):
    user = User.get_by(id=item_id)
    if not user:
        return not_found('user not found')
    if role_name in user.list_roles_names():
        return bad_request('user already has that role')
    if not user.add_role(role_name):
        return not_found('not valid role name')
    response = {
        'data': {
            'message': 'Role added to User.'
        }
    }
    return jsonify(response), 201
Ejemplo n.º 4
0
def edit_role_group(item_id):
    new_name = request.get_json().get('name')
    new_description = request.get_json().get('description')
    if not new_name or not new_description:
        return bad_request('Please provide new name or new description')

    role_group = RoleGroup.get_by(id=item_id)
    if not role_group:
        return not_found('item not found')

    try:
        role_group.name = new_name
        role_group.description = new_description
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return bad_request('already in DB')

    response = {
        'data': {
            'url': url_for('.get_role_group', item_id=role_group.id,
                           _external=True),
        }
    }
    return jsonify(response)
Ejemplo n.º 5
0
def remove_role_from_user(item_id, role_name):
    user = User.get_by(id=item_id)
    if not user:
        return not_found('user not found')
    if role_name not in user.list_roles_names():
        return bad_request('user does not has that role')
    if not user.remove_role(role_name):
        if len(user.roles) == 1:
            return bad_request('user only has that role! cannot be removed')
        else:
            return not_found('not valid role name')
    response = {
        'data': {
            'message': 'Role successfully removed from User.'
        }
    }
    return jsonify(response), 204
Ejemplo n.º 6
0
def get_employee(emp_id:int) -> Union[Dict[str, str], Tuple[Response, int, Dict[str,str]]]:
    try:
        emp:Employee = db.session.query(Employee).filter_by(emp_id=emp_id).first_or_404()
        return jsonify({'data': emp.serialize}), 200, {'Content-Type': 'application/json'}

    except Exception as ex:
        print(ex)
        return not_found('Employee does not exist')
Ejemplo n.º 7
0
def deactivate_user(item_id):
    user = User.get_by(id=item_id)
    if not user:
        return not_found('user not found')
    user.set_inactive()
    response = {
        'data': {
            'message': 'User successfully deactivated.'
        }
    }
    current_app.logger.info('User deactivated %s', user)
    return jsonify(response)
Ejemplo n.º 8
0
def delete_role(item_id):
    role = Role.get_by(id=item_id)
    if not role:
        return not_found('item not found')
    role.set_erased()
    response = {
        'data': {
            'url': url_for('.delete_role', item_id=item_id, _external=True),
            'message': 'deleted',
        }
    }
    current_app.logger.info('Role deleted %s', role)
    return jsonify(response), 204
Ejemplo n.º 9
0
    def delete(self, bucketlist_id, item_id):
        """
        Delete an item in a Bucketlist
        """
        bucketlist = Bucketlist.query.filter_by(id=bucketlist_id,
                                                created_by=g.user.id).first()
        bucketlist_item = Item.query.filter_by(bucketlist_id=bucketlist_id,
                                               item_id=item_id).first()

        if not bucketlist:
            return errors.not_found('Invalid bucketlist id')
        if not bucketlist_item:
            return errors.not_found('Invalid bucketlist id')
        if bucketlist.created_by != g.user.id:
            return errors.forbidden('Your not authorized to perfome deletion')

        db.session.delete(bucketlist_item)
        db.session.commit()
        return ({
            'message':
            'bucketlist with id {} has been deleted'.format(item_id)
        }, 200)
Ejemplo n.º 10
0
def delete_role_group(item_id):
    role_group = RoleGroup.get_by(id=item_id, erased=False)
    if not role_group:
        return not_found('item not found')
    role_group.set_erased()
    response = {
        'data': {
            'url': url_for('.delete_role_group', item_id=item_id, _external=True),
            'message': 'success',
        }
    }
    current_app.logger.info('Role group deleted %s', role_group)
    return jsonify(response), 204
Ejemplo n.º 11
0
def delete_user(item_id):
    user = User.get_by(id=item_id)
    if not user:
        return not_found('item not found')
    user.set_erased()
    response = {
        'data': {
            'url': url_for('.delete_role', item_id=item_id, _external=True),
            'message': 'deleted',
        }
    }
    current_app.logger.info('User deleted %s', user)
    return jsonify(response), 204
Ejemplo n.º 12
0
    def post(self, bucketlist_id):
        """
        Creates items to a specific bucketlist
        """

        args = self.reqparse.parse_args()
        name = args['name']
        bucketlist = Bucketlist.query.filter_by(id=bucketlist_id,
                                                created_by=g.user.id).first()

        if not bucketlist:
            return errors.not_found(
                'Sorry couldnt find bucketlist that matches id {}'.format(
                    bucketlist_id))

        existent_item = (Item.query.filter_by(bucketlist_id=bucketlist_id,
                                              name=name)).first()
        if existent_item:
            return errors.Conflict('item already exists')
        last_existent_item = (Item.query.filter_by(
            bucketlist_id=bucketlist_id).order_by(db.desc(Item.item_id)))
        try:
            prev_item_id = last_existent_item[0].item_id
        except IndexError:
            prev_item_id = 0

        if bucketlist.created_by == g.user.id:
            new_item = Item(name=name,
                            item_id=prev_item_id + 1,
                            bucketlist_id=bucketlist_id)
            db.session.add(new_item)
            db.session.commit()
            return ({
                'message': 'New bucketlist item created successfully',
                'bucketlist': marshal(new_item, bucketlist_item_field)
            }, 201)
        else:
            return errors.unauthorized(
                'Your not authorised to access this item!')
        if Item.query.filter_by(name=args['item_name']).first():
            return errors.Conflict('Item already exists')
        if not args['name']:
            return errors.bad_request('Please provide an item name')
Ejemplo n.º 13
0
def change_username(item_id):
    new_username = request.get_json().get('username')
    if not new_username:
        return bad_request('Please provide username')
    if not User.is_valid_username(new_username):
        return bad_request('not valid username')

    user = User.get_by(id=item_id)
    if not user:
        return not_found('item not found')
    user.username = new_username
    db.session.commit()

    response = {
        'data': {
            'message': 'updated',
        }
    }
    return jsonify(response)
Ejemplo n.º 14
0
def edit_role(item_id):
    new_name = request.get_json().get('name')
    new_description = request.get_json().get('description')
    new_role_group_id = request.get_json().get('role_group_id')
    new_role_group_name = request.get_json().get('role_group_name')
    if not new_name and not new_description and \
            (not new_role_group_id or not new_role_group_name):
        return bad_request('Please provide new name or new description or '
                           'new role group id or name')
    role_group = None
    if new_role_group_id:
        role_group = RoleGroup.get_by(id=new_role_group_id)
    elif new_role_group_name:
        role_group = RoleGroup.get_by(name=new_role_group_name)
    if not role_group:
        return bad_request('Please provide a valid role group id or name')

    role = Role.get_by(id=item_id)
    if not role:
        return not_found('item not found')

    if Role.get_by(name=new_name):
        return bad_request('Already in DB')

    role.name = new_name
    role.description = new_description
    role.role_group = role_group
    db.session.add(role)
    db.session.commit()
    response = {
        'data': {
            'url': url_for('.get_role', item_id=item_id, _external=True),
            'message': 'modified',
        }
    }
    return jsonify(response)
Ejemplo n.º 15
0
    def delete(self, id):
        """
        Delete a single bucketlist [DELETE]

        Args:
            id :the bucketlist identifier
        Returns:
            Response of the result status
        """
        bucketlist = Bucketlist.query.filter_by(id=id,
                                                created_by=g.user.id).first()

        if bucketlist:
            if bucketlist.created_by == g.user.id:
                db.session.delete(bucketlist)
                db.session.commit()
                return ({
                    'message':
                    'bucketlist with id {} has been deleted'.format(id)
                }, 200)
            else:
                return errors.bad_request(' Unauthorised')
        else:
            return errors.not_found('Bucketlist does not exist!')
Ejemplo n.º 16
0
def get_user(id):
    """Get a single user"""
    user = User.find_by_id(id)
    if user is None:
        return not_found('User not found!')
    return jsonify(UserSchema().dump(user))
Ejemplo n.º 17
0
    def get(self, id=None):
        """
        The [GET] is used to return all bucktlists
        or a spcefic bucteklist if search parameters
        are provided

        Args:
            id :the bucketlist identifier
            q : returns specfic bucketlist based on the name
            limit:specify the number of results
        Returns:
            BucketList query
        """
        if id:
            bucket = Bucketlist.query.filter_by(id=id,
                                                created_by=g.user.id).first()
            if bucket:
                return marshal(bucket, bucketlist_field), 200
            return errors.not_found('Bucketlist not found')
        else:
            self.reqparse = reqparse.RequestParser()
            self.reqparse.add_argument('page',
                                       type=int,
                                       location='args',
                                       default=1)
            self.reqparse.add_argument('limit',
                                       type=int,
                                       default=20,
                                       location='args')
            self.reqparse.add_argument('q', type=str, location='args')
            args = self.reqparse.parse_args()
            q = args['q']
            page = args['page']
            limit = args['limit']
        # if search or query parameters are given

        # Paginates the result of passed in functions and returns as JSON(Marshal)
        # courtesy - Miguel Grinberg (blog.miguelgrinberg.com)

        if q:
            bucketlist = Bucketlist.query.filter(Bucketlist.created_by == g.user.id,
                                                 Bucketlist.name.ilike('%' + q + '%'))\
                .paginate(page, limit, False)
        else:
            bucketlist = Bucketlist.query.filter_by(created_by=g.user.id).\
                paginate(page, limit, False)
        if not bucketlist:
            return errors.not_found('Bucketlist not available')

        if bucketlist.has_next:
            next_page = request.url + '?page=' + \
                str(page + 1) + '&limit=' + str(limit)
        else:
            next_page = 'Null'
        if bucketlist.has_prev:
            prev_page = request.url + '?page=' + \
                str(page - 1) + '&limit=' + str(limit)
        else:
            prev_page = 'Null'
        return {
            'meta': {
                'next_page': next_page,
                'prev_page': prev_page,
                'total_pages': bucketlist.pages
            },
            'bucketlist': marshal(bucketlist.items, bucketlist_field)
        }, 200