def newItem():
    # If the method is POST, try to add the new record
    if request.method == "POST":
        record = Items(
            name=request.form["name"],
            catagory_id=request.form["catagory_id"],
            description=request.form["description"],
            user_id=session['user_id'])
        # Try to add the new items
        try:
            database_session.add(record)
            database_session.commit()
        except SQLAlchemyError:
            flash("Cannot edit the item! Please contact developer!")
            return redirect("/")
        # Flash the system message
        flash("Item \"%s\" has already created!" %
              (record.name,))
        return redirect("/")
    else:
        # Render the existing catagories for selection
        catagory = database_session.query(Catagory).all()
        item = None
        return render_template(
            "itemForm.html", catagory=catagory, item=item, editFlag=False)
def fbconnect():
    # If the state variable from request is not the same as the one
    # in session,
    # Reject the request
    if request.args.get('state') != session['state']:
        response = make_response(json.dunps("Invalid Request!!!"), 401)
        response.header['Content-type'] = 'application/json'
        return response
    session['logined'] = True

    # Get the server token from facebook
    clientToken = request.data
    file = open('secret.json', 'r')
    fbsecret = json.loads(file.read())
    url = 'https://graph.facebook.com/oauth/access_token?' \
        'grant_type=fb_exchange_token&client_id=%s&client_secret=%s' \
        '&fb_exchange_token=%s' % (
            fbsecret['app_id'], fbsecret['secret'], clientToken)
    http = httplib2.Http()
    result = http.request(url, 'GET')[1]
    serverToken = result.split(',')[0].split(':')[1].replace('"', '')
    session['token'] = serverToken

    # Get the user information
    userinfo_url = 'https://graph.facebook.com/v2.8/me'\
        '?access_token=%s&fields=name,id,email' % serverToken
    http = httplib2.Http()
    userinfo = json.loads(http.request(userinfo_url, 'GET')[1])
    # Attach the result to session
    session['provider'] = 'facebook'
    session['user'] = userinfo["name"]
    session['email'] = userinfo["email"]
    session['facebook_id'] = userinfo["id"]

    # Insert the user into the database
    try:
        item = database_session.query(
            User).filter_by(
            provider=session['provider'],
            provider_id=session['facebook_id']).one()
        session['user_id'] = item.id
    except NoResultFound:
            # Try to add the new catagory
        newUser = User(
            provider=session['provider'],
            provider_id=session['facebook_id'])
        try:
            database_session.add(newUser)
            database_session.flush()
            database_session.commit()
            session['user_id'] = newUser.id
        except SQLAlchemyError:
            flash("The system cannot add the user")
            return redirect("/")

    # Flash the system message
    flash('Login Successfully via %s as %s.' % (
        session['provider'], session['user']))

    return 'success'
def editItem(item_id):
    # If the method is POST, connect to the database and update it
    if request.method == "POST":
        item_update = database_session.query(Items).filter_by(id=item_id).one()
        # Check if the editing user is the user creating this item
        if item_update.user_id != session['user_id']:
            flash('You have no permession to edit item %s' % (item.name,))
            return redirect('/')
        item_update.name = request.form["name"]
        item_update.catagory_id = request.form["catagory_id"]
        item_update.description = request.form["description"]
        # Commit the changes and except the errors
        try:
            database_session.add(item_update)
            database_session.commit()
            flash("Item \"%s\" has been updated!" % (item_update.name,))
            return redirect("/")
        except SQLAlchemyError:
            flash("Cannot edit the item! Please contact developer!")
            return redirect("/")
    else:
        # Render the item edited to user
        try:
            item = database_session.query(Items).filter_by(id=item_id).join(
                Items.catagory).one()
            catagory = database_session.query(Catagory).all()
            return render_template(
                "itemForm.html", item=item, catagory=catagory, editFlag=True)
        except NoResultFound:
            flash("Cannot find the item!")
            return redirect('/')
Exemple #4
0
def deleteItem(category_name, item_name):
    loggedIn = 'access_token' in login_session \
        and login_session['access_token'] is not None
    name = ''
    user_email = ''
    if loggedIn:
        name = login_session['name']
        user_email = login_session['email']

    itemToDelete = session.query(Item).join(Category).filter(
        Category.name == category_name, Item.name == item_name).first()
    if request.method == 'POST':
        if loggedIn == False and user_email == request.form['user_email']:
            abort(403)
        session.delete(itemToDelete)
        session.commit()
        return redirect(
            url_for('showItems',
                    category_name=category_name,
                    item_name='items'))
    else:
        return render_template('catalog/deleteItem.html',
                               category_name=category_name,
                               item_name=item_name,
                               loggedIn=loggedIn,
                               name=name,
                               user_email=user_email)
Exemple #5
0
def newItem():
    loggedIn = 'access_token' in login_session \
        and login_session['access_token'] is not None
    name = ''
    user_email = ''
    if loggedIn:
        name = login_session['name']
        user_email = login_session['email']

    if request.method == 'POST':
        if loggedIn == False and user_email == request.form['user_email']:
            abort(403)

        userId = getUserID(request.form['user_email'])

        newItem = Item(name=request.form['name'],
                       description=request.form['description'],
                       category_id=request.form['category_id'],
                       user_id=userId)
        session.add(newItem)
        session.commit()
        category = session.query(Category).filter(
            Category.id == request.form['category_id']).first()
        return redirect(
            url_for('showItems',
                    category_name=category.name,
                    item_name=request.form['name']))
    else:
        categories = session.query(Category).all()
        return render_template('catalog/newItem.html',
                               categories=categories,
                               loggedIn=loggedIn,
                               name=name,
                               user_email=user_email)
Exemple #6
0
def new_contact():
    if 'email' not in session:
	    return redirect(url_for('login'))
    form = ContactForm()
    if request.method == 'POST':
        if form.validate() is False:
            return render_template('newcontact.html', form=form)
        else:
            email = session['email']
            user = db_session.query(User).filter_by(email=email).first()
            contacts = Contact()
            contacts.UserId = user.id
            if form.first_name.data and form.last_name.data:
                contacts.name = form.first_name.data+' '+form.last_name.data
            if form.email.data:
                contacts.email = form.email.data
            if form.phone_number:
                contacts.phoneNumber = form.phone_number.data
            if form.address.data:
                contacts.address = form.address.data
            db_session.add(contacts)
            db_session.commit()
            return redirect(url_for('contacts'))
    elif request.method == 'GET':
        return render_template('newcontact.html', form=form)
Exemple #7
0
def save_item(item, item_id):
    """
    Utility method for updating an existing
    item or creating a new item
    :param item:
    :param item_id:
    :return: Rendered html
    """
    # User is modifying an EXISTING item in the database
    if item_id > 0:
        item.Item.name = request.form['title']
        item.Item.description = request.form['description']
        item.Item.category_id = request.form['category']
        session.add(item.Item)
        session.commit()
        flash("Updated " + item.Item.name)
        return render_template('item_details.html',
                               item=item,
                               login_session=login_session)

    # User is creating a NEW item
    else:
        new_item = Item(name=request.form.get('title'),
                        description=request.form['description'],
                        category_id=request.form['category'],
                        user_id=login_session['userid'])
        session.add(new_item)
        session.commit()
        flash("Created " + new_item.name)
        created_item = session.query(
            Item, User).filter(Item.id == new_item.id).join(User).first()
        return render_template('item_details.html',
                               item=created_item,
                               login_session=login_session)
def newcategory():

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Get name of new category from request and check if its not an empty
    # string.
    _categoryname = request.form['newcategory']
    # Let user know he is trying to create a no name categroy and redirect to
    # item main page.
    if _categoryname == '':
        _flashmessage = 'Name of Category must not be empty!'
        flash(_flashmessage)
        return redirect(url_for('metalitems'))

    _user_id = login_session['userid']
    # In case category is valid write it to table category.
    newCategory = Category(name=_categoryname, user_id=_user_id)
    session.add(newCategory)
    session.commit()

    # Tell the user his category has been created
    _flashmessage = 'Category ' + _categoryname + ' has been created!'
    flash(_flashmessage)

    return redirect(url_for('metalitems'))
def deleteitem(itemid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    if request.method == 'GET':
        _user_id = login_session['userid']


        _itemToDelete = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()

        # Check if item to be deleted is in databes and if not tell the user.
        if _itemToDelete is None:

            _flashmessage = "Unfortunately you're not authorized to delete \
                            this item!"
            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            session.delete(_itemToDelete)
            session.commit()

            # Let the user know that his item has been deleted.
            _flashmessage = 'Item ' + _itemToDelete.title \
                + ' has been deleted.'
            flash(_flashmessage)

            # return to main page
            return redirect(url_for('metalitems'))
Exemple #10
0
def edit_item(category_name, item_name):
    category = session.query(Category).filter_by(name=category_name).one()
    edited_item = session.query(Item).filter_by(name=item_name,
                                                category_id=category.id).one()

    # Authorisation - check if current user can edit the item
    # Only a user who created an item can edit/delete it
    user_id = get_user_id(login_session['email'])
    if edited_item.user_id != user_id:
        message = json.dumps('You are not allowed to edit the item')
        response = make_response(message, 403)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Post method
    if request.method == 'POST':
        if request.form['name']:
            edited_item.name = request.form['name']
        if request.form['description']:
            edited_item.description = request.form['description']
        if request.form['category']:
            category = session.query(Category).filter_by(name=request.form
                                                         ['category']).one()
            edited_item.category = category

        session.add(edited_item)
        session.commit()
        return redirect(url_for('show_category',
                                category_name=edited_item.category.name))
    else:
        categories = session.query(Category).all()
        return render_template('edititem.html', item=edited_item,
                               categories=categories)
def try_delete():
    """
    Try to delete an item
    Called from AJAX
    """

    # Make sure something was posted
    if 'itemname' not in request.form:
        ret = {'html': "ERROR. No item selecte for delete", 'status': "ERROR"}
        return json.dumps(ret)
    itemname = request.form["itemname"]

    # redirect if not logged in
    if 'username' not in login_session:
        return redirect('/login')

    # check if user owns the item
    if not owns_item(itemname):
        ret = {'html': "ERROR. You don't own that item", 'status': "ERROR"}
        return json.dumps(ret)

    # delete item
    session.query(Item).filter(Item.item_name == itemname).delete()
    session.commit()

    ret = {'html': "Item successfully deleted!", 'status': "SUCCESS"}
    return json.dumps(ret)
def deleteitem(itemid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    if request.method == 'GET':
        _user_id = login_session['userid']

        _itemToDelete = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()

        # Check if item to be deleted is in databes and if not tell the user.
        if _itemToDelete is None:

            _flashmessage = "Unfortunately you're not authorized to delete \
                            this item!"

            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            session.delete(_itemToDelete)
            session.commit()

            # Let the user know that his item has been deleted.
            _flashmessage = 'Item ' + _itemToDelete.title \
                + ' has been deleted.'
            flash(_flashmessage)

            # return to main page
            return redirect(url_for('metalitems'))
def newcategory():

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Get name of new category from request and check if its not an empty
    # string.
    _categoryname = request.form['newcategory']
    # Let user know he is trying to create a no name categroy and redirect to
    # item main page.
    if _categoryname == '':
        _flashmessage = 'Name of Category must not be empty!'
        flash(_flashmessage)
        return redirect(url_for('metalitems'))

    _user_id = login_session['userid']
    # In case category is valid write it to table category.
    newCategory = Category(name=_categoryname, user_id=_user_id)
    session.add(newCategory)
    session.commit()

    # Tell the user his category has been created
    _flashmessage = 'Category ' + _categoryname + ' has been created!'
    flash(_flashmessage)

    return redirect(url_for('metalitems'))
Exemple #14
0
def edit_contact(contact):
    if 'email' not in session:
        return redirect(url_for('login'))
    form = ContactForm()
    contactDetail = db_session.query(Contact).filter_by(
        contactId=contact).first()
    if request.method == 'POST':
        useremail = db_session.query(User).filter_by(
            id=contactDetail.UserId).first()
        if useremail.email == session['email']:
            if form.email.data != contactDetail.email:
                contactDetail.email = form.email.data
            if form.address.data != contactDetail.address:
                contactDetail.address = form.email.data
            if form.phone_number.data != contactDetail.phoneNumber:
                contactDetail.phoneNumber = form.phone_number.data
            db_session.commit()
            flash('Contact has been updated.')
            return redirect(url_for('contacts'))
        else:
            flash('This is not your account')
            return redirect(url_for('contacts'))

    elif request.method == 'GET':
        form.first_name.content = contactDetail.name
        form.last_name.content = contactDetail.name
        form.phone_number.content = contactDetail.phoneNumber
        form.email.content = contactDetail.email
        form.address.content = contactDetail.address
        return render_template('editcontact.html',
                               contact=contactDetail,
                               form=form)
def deleteRestaurant(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if request.method == 'POST':
        session.delete(restaurant)
        session.commit()
        flash("Restaurant deleted")
        return redirect(url_for('listRestaurants'))
    return render_template('deleteRestaurant.html', restaurant=restaurant)
def addRestaurant():
    if request.method == 'POST':
        restaurant = Restaurant(name=request.form.get('name', ''))
        session.add(restaurant)
        session.commit()
        flash("Restaurant added")
        return redirect(url_for('listMenuItems', restaurant_id=restaurant.id))
    return render_template('addRestaurant.html')
def deleteMenuItem(restaurant_id, menu_id):
    menuitem = session.query(MenuItem).filter_by(id=menu_id).one()
    if request.method == 'POST':
        session.delete(menuitem)
        session.commit()
        flash("Menu-Item deleted")
        return redirect(url_for('listMenuItems', restaurant_id=restaurant_id))
    return render_template('deleteMenuItem.html', menuitem=menuitem)
def createUser():
    newUser = User(username=login_session['username'],
                   email=login_session['email'])

    session.add(newUser)
    session.commit()

    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
def editRestaurant(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if request.method == 'POST':
        restaurant.name = request.form.get('name', '')
        session.add(restaurant)
        session.commit()
        flash("Restaurant edited")
        return redirect(url_for('listRestaurants'))
    return render_template('editRestaurant.html', restaurant=restaurant)
def createUser():
    newUser = User(username=login_session[
                   'username'], email=login_session['email'])

    session.add(newUser)
    session.commit()

    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
def insert_user():
    """
    This function inserts a user into database
    """
    temp_email = login_session['email']
    temp_name = login_session['username']
    temp_pic = login_session['picture']
    temp_user = User(email=temp_email, name=temp_name, picture=temp_pic)
    session.add(temp_user)
    session.commit()
Exemple #22
0
def create_user(login_session):
    """ User helper functions
        Creates a new user in our db
    """
    new_user = User(name=login_session['username'],
                    email=login_session['email'])
    session.add(new_user)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
def try_add():
    """
    This function receives data from the create item page from ajax call
    Attempts add that item to database
    """

    # Check that user is logged in
    if 'username' not in login_session:
        ret = {'html': "Not logged in",
               'status': "ERROR"}
        return json.dumps(ret)

    # Check that values were posted
    if 'name' not in request.form or 'desc' not in request.form:
        ret = {'html': "No values given",
               'status': "ERROR"}
        return json.dumps(ret)

    # needed variables
    t_name = request.form["name"]
    t_desc = request.form["desc"]

    # check if item exists already
    # does not make sense to have more than 1 item with same name
    if session.query(Item).filter(Item.item_name == t_name).count() != 0:
        ret_str = "Sorry. "
        ret_str += t_name
        ret_str += " is already in the database"
        ret = {'html': ret_str, 'status': "ERROR"}
        return json.dumps(ret)

    # get one and only one category id
    t_cat = return_one_category(request.form["category"])
    if t_cat == "ERROR":
        ret = {'html': "Error getting category id", 'status': "ERROR"}
        return json.dumps(ret)

    # get one and only one user id
    t_user = return_one_user(login_session['email'])
    if t_user == "ERROR":
        ret = {'html': "Error getting user id", 'status': "ERROR"}
        return json.dumps(ret)

    # add to database
    t_itm = Item(item_name=t_name, description=t_desc,
                 cat_id=t_cat, creator=t_user)
    session.add(t_itm)
    session.commit()

    # Return
    ret = {'html': "Item successfully added!", 'status': "SUCCESS"}
    return json.dumps(ret)
def serializebyitemid(categoryid, itemid):

    # Check if user is authorized.
    if isauthorized() == False:
        return redirect('/welcome')

# Get items of the user filtered by categoryid.
    _items = session.query(Seri).filter_by(user_id=login_session['userid'], \
    category_id=categoryid, item_id=itemid)
    session.commit()

    # Return them as a json
    return jsonify(Metalitems=[i.serialize for i in _items])
def serializebyitemid(categoryid, itemid):

    # Check if user is authorized.
    if isauthorized() == False:
        return redirect('/welcome')

# Get items of the user filtered by categoryid.
    _items = session.query(Seri).filter_by(user_id=login_session['userid'], \
    category_id=categoryid, item_id=itemid)
    session.commit()

# Return them as a json
    return jsonify(Metalitems=[i.serialize for i in _items])
def editMenuItem(restaurant_id, menu_id):
    menuitem = session.query(MenuItem).filter_by(id=menu_id).one()
    if request.method == 'POST':
        menuitem.name = request.form.get('name', '')
        menuitem.description = request.form.get('description', '')
        menuitem.price = request.form.get('price', '')
        menuitem.course = request.form.get('course', '')
        menuitem.restaurant_id = restaurant_id
        print request.form.get('name')
        session.add(menuitem)

        session.commit()
        flash("Menu-Item edited")
        return redirect(url_for('listMenuItems', restaurant_id=restaurant_id))
    return render_template('editMenuItem.html', menuitem=menuitem)
def addMenuItem(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if request.method == 'POST':
        menuitem = MenuItem(
            name=request.form.get('name', ''),
            description=request.form.get('description', ''),
            price=request.form.get('price', ''),
            course=request.form.get('course', ''),
            restaurant_id=restaurant_id,
        )
        session.add(menuitem)
        session.commit()
        flash("Menu-Item added")
        return redirect(url_for('listMenuItems', restaurant_id=restaurant.id))
    return render_template('addMenuItem.html', restaurant=restaurant)
Exemple #28
0
def add_item():
    categories = session.query(Category).all()
    if request.method == 'POST':
        new_item = Item(
            name=request.form['name'],
            description=request.form['description'],
            category=session.query(Category).
            filter_by(name=request.form['category']).one(),
            user_id=login_session['user_id'])

        session.add(new_item)
        session.commit()

        return redirect(url_for('show_catalog'))
    else:
        return render_template('additem.html', categories=categories)
def categoryDelete(category_id):
    """Delete the category, per the users input.

    Arg:
        category_id: category to be deleted

    Result:
        redirects user to full category list, showing them category is deleted.
    """
    items = Item.by_category_id(category_id)
    for item in items:
        session.delete(item)
        session.commit()
    category = Category.by_id(category_id)
    session.delete(category)
    session.commit()
    return redirect('/')
def itemDelete(redirect_category_id, item_id=None):
    """Handles two possibilities:

    1) User clicks delete while on screen to create new item - reload
       to category list page.
    2) User clicks delete while modifying an item - remove item from
       table and reload to parent category's page.
    """
    if item_id is None:
        # User escaped from new item process
        return redirect('/')
    else:
        item = Item.by_id(item_id)
        if item:
            session.delete(item)
            session.commit()
        return redirect('/category/' + redirect_category_id)
Exemple #31
0
def ensure_user_in_database():
    """
    If app has been restarted and user still has a session
    it might be necessary to recreate the user in the
    database (especially if using in-memory database)
    """
    if 'email' in login_session:
        user_exists = session.query(
            exists().where(User.email == login_session['email'])).scalar()
        if not user_exists:
            user = User(id=login_session['userid'],
                        picture=login_session['picture'],
                        name=login_session['name'],
                        email=login_session['email'],
                        client_id=login_session['client_id'])
            session.add(user)
            session.commit()
            print("Recreated user in database")
Exemple #32
0
def delete_item_details(item_id):
    """
    Delete item for specified ID
    CSRF Token regenerated for each new page
    :param item_id:
    :return:
    """
    item = is_user_the_creator(item_id)
    item_name = item.Item.name
    if request.method == 'GET':
        return render_template('item_delete_confirm.html',
                               item_name=item_name,
                               item_id=item_id,
                               login_session=login_session,
                               csrf_token=generate_csrf_token())
    else:
        session.delete(item.Item)
        session.commit()
        flash(item_name + " deleted")
        return redirect(url_for('show_homepage'))
Exemple #33
0
def change_pass():
    if 'email' in session:
        return redirect(url_for('home'))
    form = ChangePassword()
    if request.method == 'POST':
        if form.validate() is False:
            return render_template('changepassword.html', form=form)
        else:
            user = db_session.query(User).filter_by(
                email=form.email.data).first()
            if user is not None:
                ps_hash = bcrypt.generate_password_hash(form.password.data)
                user.password = ps_hash
                db_session.commit()
                return redirect(url_for('login'))
            else:
                flash('User not in database.')
                return render_template('changepassword.html', form=form)

    elif request.method == 'GET':
        return render_template('changepassword.html', form=form)
Exemple #34
0
def delete_contact(contact):
    if 'email' not in session:
        return redirect(url_for('login'))
    form = ContactForm()
    contactDetails = db_session.query(Contact).filter_by(
        contactId=contact).first()
    if request.method == 'GET':
        return render_template('deletecontact.html', contact=contactDetails)
    if request.method == 'POST':
        useremail = db_session.query(User).filter_by(
            id=contactDetails.UserId).first()
        if useremail.email == session['email']:
            contactDetails = db_session.query(Contact).filter_by(
                contactId=contact).first()
            db_session.delete(contactDetails)
            db_session.commit()
            flash('Contact has been deleted.')
            return redirect(url_for('contacts'))
        else:
            flash('You are not the owner of this contact.')
            return redirect(url_for('login'))
def updatecategory(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Go here in case user clicks on update categroy button on metal items
    # page.
    if request.method == 'GET':
        # Get userid for query of category user whants to update
        _user_id = login_session['userid']

        # Qurey for category to update.
        _categoryToUpdate = session.query(Category).filter_by(
            id=categoryid, user_id=_user_id).first()

        # render template for editing ategory name
        return render_template('updatecategory.html',
                               categoryToUpdate=_categoryToUpdate)
# In case user clicks button update category on update category site go here.
    else:
        # Check if category name is not an empty string
        if request.form['newcategoryname'] == '':
            # If so tell user
            _flashmessage = 'Name of category must not be empty!'
            flash(_flashmessage)

        else:
            # In case propper category name is submitted, update category table
            # with it.
            session.query(Category).filter_by(id=categoryid).update(
                {"name": request.form['newcategoryname']})
            session.commit()

            # Tell user category has been updated.
            _flashmessage = 'Name of category has been changed to: ' + \
                request.form['newcategoryname']
            flash(_flashmessage)
            # Go back to main page.
        return redirect(url_for('metalitems'))
def updatecategory(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Go here in case user clicks on update categroy button on metal items
    # page.
    if request.method == 'GET':
        # Get userid for query of category user whants to update
        _user_id = login_session['userid']

        # Qurey for category to update.
        _categoryToUpdate = session.query(Category).filter_by(
            id=categoryid, user_id=_user_id).first()

        # render template for editing ategory name
        return render_template('updatecategory.html',
                               categoryToUpdate=_categoryToUpdate)
# In case user clicks button update category on update category site go here.
    else:
        # Check if category name is not an empty string
        if request.form['newcategoryname'] == '':
            # If so tell user
            _flashmessage = 'Name of category must not be empty!'
            flash(_flashmessage)

        else:
            # In case propper category name is submitted, update category table
            # with it.
            session.query(Category).filter_by(id=categoryid).update(
                {"name": request.form['newcategoryname']})
            session.commit()

            # Tell user category has been updated.
            _flashmessage = 'Name of category has been changed to: ' + \
                request.form['newcategoryname']
            flash(_flashmessage)
            # Go back to main page.
        return redirect(url_for('metalitems'))
def newitem(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # If user clicks button add item, check if item title is not an ampty
    # string. Then store the new item in table items.
    if request.method == 'POST':
        _itemtitle = request.form['newitemtitle']

        if _itemtitle == '':
            _flashmessage = 'Name of item must not be empty!'
            flash(_flashmessage)
            return render_template('newmetalitem.html', categoryid=categoryid)

        else:
            _itemdescription = request.form['newitemdescription']
            _user_id = login_session['userid']
            _newItem = Item(title=_itemtitle,
                            description=_itemdescription,
                            category_id=categoryid,
                            user_id=_user_id)
            session.add(_newItem)
            session.commit()

            # Let the user know his new item has been safed.
            _flashmessage = 'Item ' + _itemtitle + ' has been created.'
            flash(_flashmessage)
            # Return to main page.
            return redirect(url_for('metalitems'))

    # If request is not post but get go here (comming from main page
    # metalitems).
    else:

        _category = session.query(Category).filter_by(id=categoryid).first()
        return render_template('newmetalitem.html',
                               categoryid=categoryid,
                               categoryname=_category.name)
Exemple #38
0
def delete_item(category_name, item_name):
    category = session.query(Category).filter_by(name=category_name).one()
    item_to_delete = session.query(Item).filter_by(name=item_name,
                                                   category=category).one()

    # Authorisation - check if current user can edit the item
    # Only a user who created an item can edit/delete it
    user_id = get_user_id(login_session['email'])
    if item_to_delete.user_id != user_id:
        message = json.dumps('You are not allowed to delete the item')
        response = make_response(message, 403)
        response.headers['Content-Type'] = 'application/json'
        return response

    if request.method == 'POST':
        session.delete(item_to_delete)
        session.commit()
        return redirect(url_for('show_category',
                                category_name=category.name))

    else:
        return render_template('deleteitem.html', item=item_to_delete)
def newitem(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # If user clicks button add item, check if item title is not an ampty
    # string. Then store the new item in table items.
    if request.method == 'POST':
        _itemtitle = request.form['newitemtitle']

        if _itemtitle == '':
            _flashmessage = 'Name of item must not be empty!'
            flash(_flashmessage)
            return render_template('newmetalitem.html', categoryid=categoryid)

        else:
            _itemdescription = request.form['newitemdescription']
            _user_id = login_session['userid']
            _newItem = Item(title=_itemtitle, description=_itemdescription,
                            category_id=categoryid, user_id=_user_id)
            session.add(_newItem)
            session.commit()

            # Let the user know his new item has been safed.
            _flashmessage = 'Item ' + _itemtitle + ' has been created.'
            flash(_flashmessage)
            # Return to main page.
            return redirect(url_for('metalitems'))

    # If request is not post but get go here (comming from main page
    # metalitems).
    else:

        _category = session.query(Category).filter_by(
            id=categoryid).first()
        return render_template('newmetalitem.html', categoryid=categoryid,
                               categoryname=_category.name)
def try_edit():
    """
    Try to edit an item
    Called from AJAX
    """

    # Check that user is logged in
    if 'username' not in login_session:
        ret = {'html': "Not logged in",
               'status': "ERROR"}
        return json.dumps(ret)

    # make sure data was posted
    if ('name' not in request.form or 'desc' not in request.form or
            'original' not in request.form or 'category' not in request.form):
        ret = {'html': "No values given",
               'status': "ERROR"}
        return json.dumps(ret)

    # get data
    original_name = request.form["original"]
    new_name = request.form["name"]
    new_desc = request.form["desc"]
    new_cat = return_one_category(request.form["category"])

    # update data
    item = session.query(Item).filter(Item.item_name == original_name).first()
    item.item_name = new_name
    item.description = new_desc
    item.cat_id = new_cat
    session.commit()

    # return to ajax call
    ret = {'status': "SUCCESS",
           'html': "Successfully updated item"}

    return json.dumps(ret)
def deletecategory(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Make sure site is only accessible by clicking the button and not by typing
    # url in browser.
    if request.method == 'POST':

        _user_id = login_session['userid']


        _categoryToDelete = session.query(Category).filter_by(
            id=categoryid, user_id=_user_id).first()
        # Check if category to be deleted is in database. And if not, tell the
        # user.
        if _categoryToDelete is None:

                _flashmessage = "Unfortunately you're not authorized to delete \
                this category!"
                flash(_flashmessage)

                return redirect(url_for('metalitems'))
        else:

                # Tell user category has been deleted.
                _flashmessage = 'Category ' + _categoryToDelete.name \
                + ' has been delete!'
                flash(_flashmessage)

                # Do it!
                session.delete(_categoryToDelete)
                session.commit()

                return redirect(url_for('metalitems'))
def updateitem(itemid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # If request is get go here and show site where one can edit an existing
    # item.
    if request.method == 'GET':
        _user_id = login_session['userid']

        _itemToUpdate = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()
        _categories = session.query(Category).filter_by(user_id=_user_id)

        # Check if item to be updated is in database and if not let the user
        # know.
        if _itemToUpdate is None:

            _flashmessage = "Unfortunately you're not authorized to update \
                                this item!"
            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            return render_template('updatemetalitem.html',
                    itemToUpdate=_itemToUpdate, categories=_categories)

    # Go here when user has updatet his item und clicks the save button.
    else:
        _user_id = login_session['userid']

        _itemToUpdate = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()

        _newcategory = session.query(Category).filter_by(
            name=request.form['chosencategory']).first()

        # Check if item to be updated is in database or new category is in
        # database. If not tell the user.
        if _itemToUpdate is None or _newcategory is None:

            _flashmessage = "Unfortunately you're not authorized to update \
                                this item!"
            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            session.query(Item).filter_by(id=itemid).update(
                {"title": request.form['newitemtitle'],
                "description": request.form['newitemdescription'],
                "category_id": _newcategory.id})
            session.commit()

                # Let the user know that his item has been updated.
            _flashmessage = 'Item ' + _itemToUpdate.title \
                        + ' has been updated.'
            flash(_flashmessage)

            return redirect(url_for('metalitems'))
cat_brush = Category(category_name="Brushes")
cat_mats = Category(category_name="Materials")
cat_pen = Category(category_name="Pens")
session.add_all([
    cat_brush,
    cat_mats,
    cat_pen])


# Add users
user_me = User(email="*****@*****.**", name="Andrew")
session.add(user_me)


# commit to get access to ids
session.commit()


# Add 2 brushes and a pen from me

# get id corresponding to email
my_id = session.query(User).filter(User.email == "*****@*****.**")
my_id = my_id.one().id


# get category ids
brush_id = return_one_category("Brushes")
pen_id = return_one_category("Pens")

itm_paintbrush = Item(item_name="paintbrush", description="for paint",
                      cat_id=brush_id, creator=my_id)