Esempio n. 1
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 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'))
Esempio n. 4
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)
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 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 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('/')
Esempio n. 8
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)
Esempio n. 9
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)
Esempio n. 10
0
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 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 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
Esempio n. 13
0
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 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()
Esempio n. 15
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)
Esempio n. 17
0
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)
Esempio n. 18
0
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)
Esempio n. 19
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)
Esempio n. 20
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")
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 newCatagory():
    # If the method is POST, do the following
    if request.method == "POST":
        newCataName = request.form["catagory"]
        try:
            # Prevent catagory from repeating
            item = database_session.query(
                Catagory).filter_by(name=newCataName).one()
            flash("Catagory \"%s\" has already existed!" % (newCataName,))
            return redirect("/newCatagory")
        except NoResultFound:
            # Try to add the new catagory
            newCata = Catagory(name=newCataName)
            try:
                database_session.add(newCata)
                database_session.commit()
                return redirect("/")
            except SQLAlchemyError:
                flash("Cannot commit the new item! Please contact developer!")
                return redirect("/newCatagory")
    else:
        return render_template("newCatagory.html")
Esempio n. 23
0
def login_redirect():
    """
    Redirect from Amazon Login with an auth token
    :return:
    """
    next_redirect = request.args.get('next')
    access_token = request.args.get('access_token')
    d = amazon_authorization(access_token)
    print("Amazon data:", d)
    # # State token to prevent CSRF
    # state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32))
    # login_session['state'] = state
    # Find user in database by email or create new record
    user = session.query(User).filter(User.email == d['email']).first()
    if user is None:
        print("Creating new user in database")
        m = hashlib.md5()
        m.update(d['email'])
        gravatar = 'https://secure.gravatar.com/avatar/' + m.hexdigest(
        ) + '?size=35'
        user = User(name=d['name'], email=d['email'], picture=gravatar)
        session.add(user)
        session.commit()

    # Update the Amazon ID for the user if not already set
    if user.client_id != d['user_id']:
        user.client_id = d['user_id']
        session.commit()

    login_session['userid'] = user.id
    login_session['picture'] = user.picture
    login_session['name'] = user.name
    login_session['email'] = user.email
    login_session['client_id'] = user.client_id

    flash('You were successfully logged in')

    return redirect_dest(next_redirect)
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)
Esempio n. 25
0
def sign_up():
    if 'email' in session:
        return redirect(url_for('contacts'))

    form = SignUpForm()
    if request.method == 'POST':
        if form.validate() is False:
            flash('Please fill out the form completely')
            return render_template('Signup.html', form=form)
        else:
            if db_session.query(User).filter_by(email=form.email.data).first():
                flash('Email already in use')
                return render_template('Signup.html', form=form)
            else:
                pw_hash = bcrypt.generate_password_hash(form.password.data)
                users = User(form.first_name.data,
                             form.last_name.data, pw_hash,
                             form.email.data)
                db_session.add(users)
                db_session.commit()
                session['email'] = form.email.data
                return redirect(url_for('contacts'))
    elif request.method == 'GET':
        return render_template('Signup.html', form=form)
Esempio n. 26
0
def editItem(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']

    item = 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)
        item.name = request.form['name']
        item.description = request.form['description']
        item.category_id = request.form['category_id']
        session.add(item)
        session.commit()
        category = session.query(Category).filter(
            Category.id == item.category_id).first()
        return redirect(
            url_for('showItems',
                    category_name=category.name,
                    item_name=item.name))
    else:
        categories = session.query(Category).all()

        return render_template('catalog/editItem.html',
                               categories=categories,
                               category_name=category_name,
                               item_name=item_name,
                               item=item,
                               loggedIn=loggedIn,
                               name=name,
                               user_email=user_email)
from database_setup import Restaurant, MenuItem, setup, session

setup()

# Menu for UrbanBurger
restaurant1 = Restaurant(name="Urban Burger")

session.add(restaurant1)
session.commit()

menuItem2 = MenuItem(
    name="Veggie Burger",
    description="Juicy grilled veggie patty with tomato mayo and lettuce",
    price="$7.50",
    course="Entree",
    restaurant=restaurant1)

session.add(menuItem2)
session.commit()

menuItem1 = MenuItem(name="French Fries",
                     description="with garlic and parmesan",
                     price="$2.99",
                     course="Appetizer",
                     restaurant=restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(
    name="Chicken Burger",
Esempio n. 28
0
session.query(Item).delete()


# Art Supplies Store Categories
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")