def insert():
    # check if user logged in:
    if "logged_in" in session and session["logged_in"] is True:
        dsn = functions.get_dsn()
        conn = functions.getConn(dsn)
        data = functions.getListOfDorms(conn)
        if request.method == 'GET':
            return render_template('insert.html', data=data)
        else:
            try:
                roomNumber = request.form['roomNumber']
                roomType = request.form['menu-room-type']
                dormID = request.form['menu-dorm']

                #updating if/else notifications for correct input
                if dormID == "none" and roomType == 'none' and not roomNumber:
                    flash('Please choose a dorm, room type, and room number.')
                    return render_template('insert.html', data=data)
                elif dormID == "none" and roomType == 'none':
                    flash('Please choose a dorm and room type.')
                    return render_template('insert.html', data=data)
                elif dormID == "none" and not roomNumber:
                    flash('Please choose a dorm and room number.')
                    return render_template('insert.html', data=data)
                elif not roomNumber and roomType == 'none':
                    flash('Please choose a room number and room type.')
                    return render_template('insert.html', data=data)
                elif dormID == 'none':
                    flash('Please choose a dorm.')
                    return render_template('insert.html', data=data)
                elif not roomNumber:
                    flash('Please choose a room number.')
                    return render_template('insert.html', data=data)
                else:
                    # room number and dorm provided
                    msg = dormID + " " + roomNumber
                    row = functions.roomExists(conn, dormID, roomNumber,
                                               roomType)
                    if row is not None:
                        flash(msg + ' already exists')
                        return render_template('insert.html', data=data)
                    else:
                        functions.addRoom(conn, dormID, roomNumber, roomType)
                        flash(msg + ' succesfully  added.')
                        return render_template('insert.html', data=data)
            except Exception as err:
                flash('Sorry, an error occurred.')
                print err
                dsn = functions.get_dsn()
                conn = functions.getConn(dsn)
                data = functions.getListOfDorms(conn)
                return render_template('insert.html', data=data)
    else:
        flash("Please log in!")
        return redirect(url_for('login'))
def search():
    '''Displays all the user requested search results'''
    if request.method == 'POST':
        conn = functions.getConn('final_project')
        title = request.form['title']
        network = request.form['network']
        creator = request.form['creator']
        genre = request.form['genre']
        contentwarning = request.form['contentwarning']
        tag_names = request.form.getlist('tags')
        tag_vals = request.form.getlist('tag-args')

        if (title == '' and network == '' and creator == ''
                and contentwarning == '' and tag_names == '' and tag_vals == ''
                and genre == ''):
            flash("Search using at least one criteria")
            return redirect(request.referrer)

        if title:
            shows = functions.getResultsByTitle(conn, title)
            print shows
        elif network:
            shows = functions.getResultsByNetwork(conn, network)
        elif creator:
            shows = functions.getResultsByCreator(conn, creator)
        elif genre:
            shows = functions.getResultsByGenre(conn, genre)
        elif tag_names and tag_vals:
            shows = functions.getResultsByTags(conn, tag_names, tag_vals)
        elif contentwarning:
            shows = functions.getResultsByContentWarning(conn, contentwarning)
        return render_template('results.html', shows=shows)
def login():
    '''lets a user log in'''
    if request.method == 'GET':
        return render_template('login.html')
    if request.method == 'POST':
        try:
            username = request.form['username']
            passwd = request.form['password']
            conn = functions.getConn('final_project')
            userRow = functions.checkPW(conn, username)
            if userRow is None:
                flash('login incorrect (app.py 201). Try again or join')
                return redirect(url_for('login'))
            hashed = userRow['hashed']
            #strings always come out as unicode, so have to encode
            if bcrypt.hashpw(passwd.encode('utf-8'),
                             hashed.encode('utf-8')) == hashed:
                flash('successfully logged in as ' + username)
                session['username'] = username
                session['logged_in'] = True
                return redirect(url_for('index'))
            else:
                flash('login incorrect. Try again or join')
                return redirect(url_for('login'))
        except Exception as err:
            print 'form submission error ' + str(err)
            return redirect(url_for('login'))
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        try:
            dsn = functions.get_dsn()
            conn = functions.getConn(dsn)
            email = request.form["email"]
            password = request.form["password"]
            emailsuccess = functions.emailcorrect(conn, email)

            if emailsuccess:
                passwordsuccess = functions.passwordcorrect(
                    conn, email, password)
                if passwordsuccess:
                    flash('Successfully logged in as ' + email)

                    #session will be updated in the later
                    session['email'] = email
                    session['logged_in'] = True
                    session['visits'] = 1  #fixed as 1?

                    return redirect(url_for('insert', email=email))
                else:
                    #no match between username and password
                    flash('Your password is incorrect. Please try again.')
                    return redirect(url_for('login'))
            else:
                #the email does not exist
                flash(
                    'The email you entered does not exist. Please try again.')
                return redirect(url_for('login'))
        except Exception as err:
            flash('form submission error ' + str(err))
            return redirect(url_for('login'))
Пример #5
0
def deleteUser(bnumber):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))
    conn = functions.getConn(db)
    functions.deleteUser(conn, bnumber)
    flash('User (%s) was deleted successfully' % bnumber)
    return redirect(url_for('index'))
Пример #6
0
def insertUser():
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    message = ''
    if request.method == 'POST':
        bnumber = request.form['bnumber']
        if len(bnumber) != 9:
            message = 'BNUMBER must be valid'
            flash(message)
            return redirect(request.referrer)
        exists = functions.getUser(conn, bnumber)
        if exists:
            message = 'error: user exists; User with bnumber: %s is already in database' % bnumber
        else:
            email = request.form['email']
            name = request.form['user_name']
            phonenum = request.form['phonenum']
            functions.insertUser(conn, bnumber, email, name, phonenum)
            message = 'User %s inserted.' % name
        flash(message)
        return redirect(url_for('index'))
    else:
        attributes = session['CAS_ATTRIBUTES']
        return render_template('insertUser.html', attributes=attributes)
Пример #7
0
def listingecho():
    conn = functions.getConn(db)
    form = request.form
    pid = functions.insertListing(conn, form.get("user"), form.get("street1"),
                                  form.get("street2"), form.get("city"),
                                  form.get("state"), form.get("zip"),
                                  form.get("country"), form.get("maxguest"),
                                  form.get("start"), form.get("end"))

    if ('pic' in request.files):
        f = request.files['pic']

        user_filename = f.filename
        ext = user_filename.split('.')[-1]
        filename = secure_filename('{}.{}'.format(pid, ext))
        pathname = os.path.join(app.config['UPLOADS'], filename)
        if (imghdr.what(f) is not None):
            f.save(pathname)
            functions.insertPic(conn, pid, filename)
            return render_template('listingconfirmation.html',
                                   form=form,
                                   src=url_for('pic', pid=pid))
        flashMessage = "Must be a valid image type"

    flash(flashMessage)
    return render_template('listingconfirmation.html', form=form, src="")
Пример #8
0
def editListing(pid):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    if (request.method == 'GET'):
        guestRequest = functions.getPlace(conn, pid)
        return render_template('editListing.html', request=guestRequest)
    else:
        form = request.form
        functions.editListing(conn, pid, form)
        if ('pic' in request.files):
            print("hello")
            f = request.files['pic']
            user_filename = f.filename
            ext = user_filename.split('.')[-1]
            filename = secure_filename('{}.{}'.format(pid, ext))
            pathname = os.path.join(app.config['UPLOADS'], filename)
            if (imghdr.what(f) is not None):
                f.save(pathname)
                functions.insertPic(conn, pid, filename)

        flash("Updated successfully!")
        return redirect(
            url_for('profile', bnumber=session['CAS_ATTRIBUTES']['cas:id']))
Пример #9
0
def cart():
    print session['cart']
    conn = functions.getConn('tabtracker')
    cart  = session['cart']
    if request.method == 'POST':
        miid=request.form.get('miid')
        if request.form.get('quantity'):
            newQuantity=request.form.get('quantity')
            if int(newQuantity)==0:
                cart.pop(miid)
                print "item removed from cart!"
                session['cart'] = cart
                return jsonify({'miid':miid,'quantity':True})
            cart[miid]['quantity'] = newQuantity
            cq = cart[miid]['quantity']
            print cart
            session['cart'] = cart
            return jsonify({'miid':miid,'quantity':cq})
        item = functions.getMenuItem(conn,miid)
        if miid in cart:
            cart[miid]['quantity'] += 1
        else:
            #extras = {}
            item['extras'] = {}
            print item
            cart[miid] = item
        print cart
        session['cart'] = cart
        return jsonify(item)
    
    return render_template('shopping_cart_page.html')
Пример #10
0
def index():
    conn = functions.getConn('tabtracker')
    if session.get('staffId'):
        session.pop('staffId')
    if session.get('username'):
        session.pop('username')
    return render_template('index.html')
Пример #11
0
def recent_orders(username):
    conn = functions.getConn('tabtracker')
    if not session.get('username'):
        access_tab(username)
    if request.method == 'POST':
        form = request.form.to_dict(flat=False)
        if form:
            print form
            form = [{form.keys()[j]: form.values()[j][i] for j in range(len(form))} for i in range(len(form.values()[0]))]
            print form
            
            functions.addOrder(conn,form,username)
            orders = functions.getRecentOrders(conn,username)
            items = functions.getOrderItems(conn,username)
            user = functions.getUser(conn,username)
            if session['username'] in session['currentOrders']:
                session['currentOrders'][session['username']].update(session['cart'])
            else:
                session['currentOrders'][session['username']] = session['cart']
            print session['currentOrders'][session['username']]
            clearCart()
            return render_template('recent_orders.html',orders=orders, items=items, user=user)
        else:
            return redirect(request.referrer)

    orders = functions.getRecentOrders(conn,username)
    items = functions.getOrderItems(conn,username)
    user = functions.getUser(conn,username)
    return render_template('recent_orders.html',orders=orders, items=items, user=user)
Пример #12
0
def report(bnumber):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    if request.method == "GET":
        return render_template('report.html')
    if request.method == "POST":
        try:
            # throw error if there's trouble
            sender = session['CAS_ATTRIBUTES']['cas:mail']
            recipient = "*****@*****.**"
            subject = bnumber + ": " + request.form['issues']
            body = request.form['report']
            # print(['form',sender,recipient,subject,body])
            msg = Message(subject=subject,
                          sender=sender,
                          recipients=[recipient],
                          body=body)
            # print(['msg',msg])
            mail.send(msg)
            flash('email sent successfully')
            return render_template('reportconfirmation.html')

        except Exception as err:
            print(['err', err])
            flash('form submission error' + str(err))
            return redirect(url_for('index'))
def signup():
    '''lets a user to sign up/join'''
    if request.method == 'GET':
        return render_template('signup.html')
    if request.method == 'POST':
        try:
            username = request.form['username']
            passwd1 = request.form['password1']
            passwd2 = request.form['password2']
            if passwd1 != passwd2:
                flash('passwords do not match')
                return redirect(url_for('signup'))
            hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt())
            conn = functions.getConn('final_project')
            userRow = functions.checkUsername(conn, username)
            if userRow is not None:  #check if username exists in the database
                flash('That username is taken')
                return redirect(url_for('signup'))
            functions.insertUser(conn, username, hashed)
            session['username'] = username
            session['logged_in'] = True
            flash('signed up and logged in as ' + username)
            return redirect(url_for('index'))
        except Exception as err:
            print('form submission error ' + str(err))
            return redirect(url_for('signup'))
Пример #14
0
def set_staff():
    conn = functions.getConn('tabtracker')
    password="******"
    hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    functions.setDefaultPwd(conn,hashed)
    staff = functions.allStaff(conn)
    print staff
    return staff
Пример #15
0
def deleteAvailabilityAjax():
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    aid = request.form['aid']
    conn = functions.getConn(db)
    functions.deleteAvailability(conn, aid)
    return jsonify(aid=aid, error=False)
Пример #16
0
def requestecho():
    conn = functions.getConn(db)
    form = request.form
    functions.insertRequest(conn, form.get("user"), form.get("city"),
                            form.get("country"), form.get("guestnum"),
                            form.get("start"), form.get("end"))

    return render_template('requestconfirmation.html', form=form)
Пример #17
0
def tabs():
    if not session.get('staffId'):
        return redirect(url_for('index'))
    if session.get('username'):
        print leave_tab()
    conn = functions.getConn('tabtracker')
    users = functions.getAllUsers(conn)
    return render_template('userTabs.html', users=users)
Пример #18
0
def listing():
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    attributes = session['CAS_ATTRIBUTES']
    bnumber = attributes['cas:id']
    conn = functions.getConn(db)
    user = functions.getUser(conn, bnumber)
    return render_template('listingform.html', user=user)
Пример #19
0
def deleteRequest(rid):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    functions.deleteRequest(conn, rid)

    return redirect(
        url_for('profile', bnumber=session['CAS_ATTRIBUTES']['cas:id']))
Пример #20
0
def deleteAvailability(aid):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    availability = functions.getAvailability(conn, aid)
    functions.deleteAvailability(conn, aid)

    return redirect(url_for('place', pid=availability['pid']))
def index():
    '''Main page'''
    conn = functions.getConn('final_project')
    networks = functions.getAllNetworks(conn)
    contentwarnings = functions.getAllWarnings(conn)
    print 'app.py line 33 session ------'
    print session
    return render_template('home.html',
                           networks=networks,
                           contentwarnings=contentwarnings)
Пример #22
0
def access_tab(username):
    print username
    conn = functions.getConn('tabtracker')
    #sessId = functions.newSession(conn,username)
    session['username'] = username
    #session['sessId'] = sessId
    menu = functions.getAllMenuItems(conn)
    session['cart'] = {}
    print "accessing the tab of " + session['username'] + "!"
    return redirect(url_for('recent_orders', username=session['username']))
Пример #23
0
def searchR(query, guest):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    aRequest = functions.searchRequest(conn, query)
    return render_template('searchrequest.html',
                           requests=aRequest,
                           query=query,
                           guest=guest)
Пример #24
0
def addAvailability(pid):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)
    form = request.form
    start = form.get('start')
    end = form.get('end')
    functions.insertAvailability(conn, pid, start, end)

    return redirect(url_for('place', pid=pid))
Пример #25
0
def index():
    if ('CAS_USERNAME' in session):
        attributes = session['CAS_ATTRIBUTES']
        bnumber = attributes['cas:id']

        conn = functions.getConn(db)
        user = functions.getUser(conn, bnumber)
        if not user:
            return redirect("insertUser")

    return render_template('home.html')
Пример #26
0
def search(query, guest):
    if ('CAS_USERNAME' not in session):
        return redirect(url_for("index"))

    conn = functions.getConn(db)

    places = functions.searchPlace(conn, query, guest)
    return render_template('search.html',
                           listings=places,
                           guest=guest,
                           query=query)
Пример #27
0
def order():
    conn = functions.getConn('tabtracker')
    if request.method=='POST':
        miid = request.form.get('miid')
        ingred = functions.getIngredients(conn,miid)
        print ingred
        extra = functions.getAllIngredients(conn)
        
        return jsonify({'ingred':ingred, 'extra':extra})
    items = functions.getAllMenuItems(conn)
    return render_template('order_form.html', items=items)
def edit(sid):
    '''Edits/updates profile page of the show based on show id (sid)'''
    conn = functions.getConn('final_project')
    if request.method == 'GET':
        if 'username' not in session:
            flash('you are not logged in. Please login or join')
            return redirect(url_for('login'))
        show = functions.getShow(conn, sid)
        creators = functions.getCreators(conn, sid)
        warnings = functions.getWarnings(conn, sid)
        genres = functions.getGenres(conn, sid)
        tags = functions.getTags(conn, sid)
        return render_template('edit.html',
                               show=show,
                               creators=creators,
                               warnings=warnings,
                               tags=tags,
                               genres=genres)
    if request.method == 'POST':
        newtitle = request.form['show-title']
        newnetwork = request.form['show-network']
        newyear = request.form['show-release']
        newdesc = request.form['show-description']
        newscript = request.form['show-script']
        try:
            newfile = request.files['file']
        except:
            newfile = False
        newgenrelist = request.form.getlist('show-genres')
        newcreators = request.form.getlist('show-creators')
        newcwList = request.form.getlist('show-warnings')
        tag_names = request.form.getlist('tags')
        tag_vals = request.form.getlist('tag-vals')
        if newfile:
            filename = functions.isValidScriptType(newfile, newtitle)
            if filename:
                newscript = filename
                print("*** NEW SCRIPT FILE ***")
                flash(
                    '''New script uploaded. Please hit SHIFT-REFRESH to refresh 
                the cache and see the new script if it has not updated.''')
            else:  # file is not a valid type
                return redirect(request.referrer)
        else:
            print("No new script")
            if 'http' not in newscript:
                flash('''Invalid script link. Please include http:// at the 
                        beginning of the link.''')
                return redirect(request.referrer)
        functions.update(conn, sid, newtitle, newyear, newnetwork,
                         newgenrelist, newcwList, newscript, newdesc,
                         newcreators, tag_names, tag_vals)
        return redirect(url_for('profile', sid=sid))
def script(sid):
    ''' This may be a kinda hacky thing to do, but if a script is local, aka
        stored in our filesystem, then we render it the normal way by passing
        the filepath to our profile template. If the script is external, aka
        we stored a http link in our database, then we do a straight redirect
        to that stored URL. '''
    conn = functions.getConn('final_project')
    curs = conn.cursor(MySQLdb.cursors.DictCursor)
    script, is_local = functions.getScript(conn, sid)
    print("**************** IN SCRIPT ROUTE ****************")
    print(script, is_local)
    print("ISSS LOCALL:", is_local)
    return script if (is_local == "local") else redirect(script)
def search():
    # check if user logged in:
    if "logged_in" in session and session["logged_in"] is True:
        dsn = functions.get_dsn()
        conn = functions.getConn(dsn)

        if request.method == 'GET':
            return render_template('search.html',
                                   dormarray=functions.getListOfDorms(conn))

        elif request.form[
                'submit'] == 'dorm':  #if user search room through dorm name
            counter = -1
            roomList = []
            dormList = request.form.getlist("dorm")
            for dorm in dormList:
                counter += 1
                roomList += functions.getListOfRoomsbyDorm(
                    conn, dormList[counter])

            if not roomList:
                flash("No Result Matches Your Request!")
                return render_template(
                    'search.html', dormarray=functions.getListOfDorms(conn))
            else:
                return render_template('result.html', roomArray=roomList)

        elif request.form[
                'submit'] == "filter":  #if user search room through other filters
            location = request.form['location']
            dormType = request.form['dormType']
            roomType = request.form['roomType']
            # Below to be added later
            # special = request.form['special']
            # gym = request.form['gym']
            # dinningHall = request.form['dinningHall']
            # rating = request.form['rating']

            roomList = functions.getListOfRoomsbyFilter(
                conn, location, dormType, roomType)

            if not roomList:
                flash("No Result Matches Your Request!")
                return render_template(
                    'search.html', dormarray=functions.getListOfDorms(conn))
            else:
                return render_template('result.html', roomArray=roomList)

    else:
        flash("Please log in!")
        return redirect(url_for('login'))