Esempio n. 1
0
def test_get_close_db(app):
    with app.app_context():
        db = get_db()
        assert db is get_db()
    with pytest.raises(pymysql.Error) as e:
        db.execute("SELECT 1")
    assert 'closed' in str(e)
Esempio n. 2
0
def addplane():
    """
    Return add plane page. Airline staffs can add planes for their company.

    Args:
        None

    Returns:
        Airline Staff add flights page
    """
    cursor = get_cursor()
    cursor.execute(
        "SELECT airplane_id, seat FROM airplane WHERE airline = %s ",
        (g.user[5]))
    airplanes = cursor.fetchall()
    if request.method == "POST":
        error = None
        seat = request.form['seat']
        db = get_db()
        cursor = get_cursor()
        if int(seat) <= 0:
            error = "Number should be greater than 0."
        if error is None:
            try:
                cursor.execute(
                    "INSERT INTO airplane (airline, seat) values (%s, %s)",
                    (g.user[5], seat))
                db.commit()
                return redirect(url_for('a.confirm', action="Add airplane"))
            except pymysql.Error as e:
                db.rollback()
        flash(error)
    return render_template('a/addplane.html', airplanes=airplanes)
Esempio n. 3
0
def addairport():
    """
    Return add airport page. Airline staffs can add airports for their company.

    Args:
        None

    Returns:
        Airline Staff add airport page
    """

    if request.method == "POST":
        error = None
        name = request.form['name']
        city = request.form['city']
        db = get_db()
        cursor = get_cursor()
        cursor.execute("SELECT * FROM airport WHERE name = %s", (name, ))
        if cursor.fetchone() is not None:
            error = "The airport is already in the system"
            flash(error)
        else:
            try:
                cursor.execute(
                    "INSERT INTO airport (name, city) values (%s, %s)",
                    (name, city))
                db.commit()
                return redirect(url_for('a.confirm', action="Add airport"))
            except pymysql.Error as e:
                db.rollback()
                flash(e)
    return render_template('a/addairport.html')
def app():
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({'TESTING': True, 'DATABASE': db_path})

    with app.app_context():
        init_db()
        cursor = get_db().cursor()
        queries = str(_data_sql).split(';')[:-1]
        for query in queries:
            cursor.execute(query)
    yield app

    os.close(db_fd)
    os.unlink(db_path)
Esempio n. 5
0
def settings():
    """	
    Airline Staff Settings Page. Airline staff can see his/her information, including Name, Email, Phone Number, etc. Airline Staff can also add phone numbers.	
    	
    Args:	
        None.	
    	
    Returns:	
        Airline Staff settings page	
    """
    db = get_db()
    cursor = db.cursor()
    error = None
    if request.method == "POST":
        phone_number = request.form["phone_number"]
        if phone_number != "":
            cursor.execute("SELECT * FROM staff_phone WHERE phone_number = %s",
                           (phone_number))
            if cursor.fetchone() is not None:
                error = "Phone number already in system"
            if error is None:
                try:
                    cursor.execute(
                        "INSERT INTO staff_phone (phone_number, username) values (%s, %s)",
                        (phone_number, g.user[0]))
                    db.commit()
                except pymysql.Error as e:
                    db.rollback()
            flash(error)
    username = g.user[0]
    fname = g.user[2]
    lname = g.user[3]
    bday = g.user[4]
    airline = g.user[5]
    cursor.execute("SELECT phone_number FROM staff_phone WHERE username = %s",
                   (g.user[0]))
    phones = cursor.fetchall()
    return render_template("a/settings.html",
                           username=username,
                           fname=fname,
                           lname=lname,
                           bday=bday,
                           airline=airline,
                           phones=phones)
Esempio n. 6
0
def addflights():
    """
    Return add flights page. Airline staffs can add flights for their company.

    Args:
        None

    Returns:
        Airline Staff add flights page
    """
    if request.method == "POST":
        error = None
        airline = g.user[5]
        airplane_id = request.form['airplane_id']
        base_price = request.form['base_price']
        flight_status = request.form['flight_status']
        dept_time = request.form['dept_date'] + ' ' + request.form['dept_time']
        arrv_time = request.form['arrv_date'] + ' ' + request.form['arrv_time']
        dept_airport = request.form['dept_airport']
        arrv_airport = request.form['arrv_airport']
        try:
            db = get_db()
            cursor = db.cursor()
            cursor.execute(
                "INSERT INTO flight (airline, airplane_id, base_price, flight_status, dept_time, arrv_time, dept_airport, arrv_airport) values (%s,%s,%s,%s,%s,%s,%s,%s)",
                (airline, airplane_id, base_price, flight_status, dept_time,
                 arrv_time, dept_airport, arrv_airport))
            db.commit()
            return redirect(url_for('a.confirm', action="Add Flight"))
        except pymysql.Error as e:
            flash(e)
            db.rollback()

    cursor = get_cursor()
    # select all airplane of the company
    cursor.execute("SELECT airplane_id FROM airplane WHERE airline = %s",
                   (g.user[5]))
    airplanes = cursor.fetchall()
    # select all airports
    cursor.execute("SELECT name FROM airport")
    airports = cursor.fetchall()
    return render_template('a/addflights.html',
                           airplanes=airplanes,
                           airports=airports)
Esempio n. 7
0
def settings():
    """
    Customer Settings Page. Can add phone number. 

    Args:
        None.

    Returns:
        Airline Staff settings page
    """
    db = get_db()
    cursor = db.cursor()
    error = None
    if request.method == "POST":
        phone_number = request.form["phone_number"]
        cursor.execute(
            "SELECT * FROM customer_phone WHERE phone= %s", (phone_number))
        if cursor.fetchone() is not None:
            error = "Phone number already in system"
        if error is None:
            try:
                cursor.execute(
                    "INSERT INTO customer_phone (phone, email) values (%s, %s)", (phone_number, g.user[0]))
                db.commit()
            except pymysql.Error as e:
                db.rollback()
        flash(error)
    email = g.user[0]
    name = g.user[1]
    building_number = g.user[3]
    street = g.user[4]
    city = g.user[5]
    state = g.user[6]
    passport_number = g.user[7]
    passport_exp = g.user[8]
    passport_country = g.user[9]
    bday = g.user[10]
    cursor.execute(
        "SELECT phone FROM customer_phone WHERE email = %s", (g.user[0]))
    phones = cursor.fetchall()
    return render_template("c/settings.html", phones=phones, email=email, name=name, building_number=building_number, street=street, city=city, state=state, passport_number=passport_number, passport_country=passport_country, passport_exp=passport_exp, bday=bday)
Esempio n. 8
0
def flight_info(flight_id):
    """
    Return certain flight info. Displaying all the passengers.
    Args:
        None

    Returns:
        Airline Staff flights page
    """
    if request.method == "POST":
        error = None
        flight_id = request.form["flight_id"]
        status = request.form["status"]
        db = get_db()
        cursor = db.cursor()
        try:
            cursor.execute(
                "UPDATE flight SET flight_status=%s WHERE flight_id = %s",
                (status, flight_id))
            db.commit()
            return redirect(url_for('a.confirm', action="Change Status"))
        except pymysql.Error as e:
            db.rollback()
            flash(e)

    cursor = get_cursor()
    cursor.execute(
        "SELECT email, name FROM customer JOIN ticket ON email = customer_email WHERE airline = %s AND flight_id = %s",
        (
            g.user[5],
            flight_id,
        ))
    customers = cursor.fetchall()
    return render_template("a/flight_info.html",
                           flight_id=flight_id,
                           customers=customers)
Esempio n. 9
0
def index():
    """
    Index page for the site. Users can search flights 
    
    Args:
        None.
    
    Returns:
        Index Page.
    """
    # initialize the search result to be empty

    n_flights = 'n' # n for null
    b_n_flights = 'o' # stands for one way
    db = get_db()
    cursor = db.cursor()
    # cursor.execute("SELECT distinct dept_airport from flight")
    # dept_airport = cursor.fetchall()
    # cursor.execute("SELECT distinct arrv_airport from flight")
    cursor.execute("SELECT name FROM airport")
    dept_airport = arrv_airport = cursor.fetchall()
    cursor.execute("SELECT name FROM airline")
    airlines = cursor.fetchall()
    if request.method == "POST": # from search form submit
        if request.form['content'] == "trip":
            f_dept_airport = request.form['dept_airport'] # search form names
            f_dept_time = request.form['dept_time']

            f_arrv_airport= request.form['arrv_airport']
            cursor.execute("SELECT * from `flight` WHERE dept_airport= %s AND arrv_airport = %s and DATE(dept_time) = %s",(f_dept_airport, f_arrv_airport,f_dept_time))     
            flights = cursor.fetchall() # all the planes that matches the result
            n_flights = []
            if flights:
                for flight in flights:
                    flight = list(flight)
                    base_price = flight[3]
                    # find out how many tickets are sold
                    cursor.execute("SELECT COUNT(flight_id) FROM ticket WHERE flight_id = %s GROUP BY flight_id", flight[0])
                    ticket_sold = cursor.fetchone()[0]
                    # find out how many seats are available
                    cursor.execute("SELECT seat FROM airplane where airplane_id = %s",(flight[2]))
                    seat = cursor.fetchone()[0]
                    if ticket_sold == seat:
                        price = 'Sold Out'
                    elif ticket_sold / seat >= 0.7:
                        price = int(base_price * 1.2)  # when 70% of tickets are sold, raise the price
                    else:
                        price = base_price
                    flight = [flight[1], flight[5], flight[6], price, flight[0]] # airline, dept_time, arrv_time, price, flight_id
                    n_flights.append(flight)
            else:
                n_flights = 'e' # e for empty
            # if comming back
            if request.form['trip'] == 'twoway':
                f_back_date = request.form['back_date']
                cursor.execute("SELECT * from `flight` WHERE dept_airport= %s AND arrv_airport = %s and DATE(dept_time) = %s",(f_arrv_airport, f_dept_airport,f_back_date))     
                b_flights = cursor.fetchall() # all the planes that matches the result
                b_n_flights = []
                if b_flights:
                    for b_flight in b_flights:
                        b_flight = list(b_flight)
                        base_price = b_flight[3]
                        # find out how many tickets are sold
                        cursor.execute("SELECT * FROM ticket WHERE flight_id = %s", b_flight[0])
                        ticket_sold = len(cursor.fetchall())
                        # find out how many seats are available
                        cursor.execute("SELECT seat FROM airplane where airplane_id = %s",(b_flight[2]))
                        seat = cursor.fetchone()[0]
                        if ticket_sold == seat:
                            price = 'Sold Out'
                        elif ticket_sold / seat >= 0.7:
                            price = int(base_price * 1.2)  # when 70% of tickets are sold, raise the price
                        else:
                            price = base_price
                        b_flight = [b_flight[1], b_flight[5], b_flight[6], price, b_flight[0]] # airline, dept_time, arrv_time, price, flight_id
                        b_n_flights.append(b_flight)
                else:
                    b_n_flights = 'e'
        elif request.form['content'] == "flight":
            f_airline = request.form['airline']
            f_flight_id = request.form['flight_id']
            f_dept_date = request.form['dept_date']
            f_arrv_date = request.form['arrv_date']
            cursor.execute("SELECT * from `flight` WHERE flight_id = %s AND DATE(dept_time)= %s AND DATE(arrv_time)= %s and airline = %s",(f_flight_id, f_dept_date, f_arrv_date,f_airline))     
            flights = cursor.fetchall() # all the planes that matches the result
            n_flights = []
            if flights:
                for flight in flights:
                    flight = list(flight)
                    base_price = flight[3]
                    # find out how many tickets are sold
                    cursor.execute("SELECT * FROM ticket WHERE flight_id = %s", flight[0])
                    ticket_sold = len(cursor.fetchall())
                    # find out how many seats are available
                    cursor.execute("SELECT seat FROM airplane where airplane_id = %s",(flight[2]))
                    seat = cursor.fetchone()[0]
                    if ticket_sold == seat:
                        price = 'Sold Out'
                    elif ticket_sold / seat >= 0.7:
                        price = int(base_price * 1.2)  # when 70% of tickets are sold, raise the price
                    else:
                        price = base_price
                    flight = [flight[1], flight[5], flight[6], price, flight[0]] # airline, dept_time, arrv_time, price, flight_id
                    n_flights.append(flight)
    return render_template('index.html', dept_airport = dept_airport, arrv_airport = arrv_airport, result= n_flights, back = b_n_flights, airlines = airlines)
Esempio n. 10
0
def search():
    """
    Search future flights    

    Args:
        None
    
    Returns:
        Booking Agent index page
    """
    n_flights = 'e'
    db = get_db()
    cursor = db.cursor()
    cursor.execute("SELECT distinct dept_airport from flight")
    dept_airport = cursor.fetchall()
    cursor.execute("SELECT distinct arrv_airport from flight")
    arrv_airport = cursor.fetchall()
    b_n_flights = None
    if request.method == "POST":  # from search form submit

        f_dept_airport = request.form['dept_airport']  # search form names
        f_dept_time = request.form['dept_time']

        f_arrv_airport = request.form['arrv_airport']
        cursor.execute(
            "SELECT * from `flight` WHERE dept_airport= %s AND arrv_airport = %s and DATE(dept_time) = %s",
            (f_dept_airport, f_arrv_airport, f_dept_time))
        flights = cursor.fetchall()  # all the planes that matches the result
        n_flights = []
        for flight in flights:
            flight = list(flight)
            base_price = flight[3]
            # find out how many tickets are sold
            cursor.execute("SELECT * FROM ticket WHERE flight_id = %s",
                           flight[0])
            ticket_sold = len(cursor.fetchall())
            # find out how many seats are available
            cursor.execute("SELECT seat FROM airplane where airplane_id = %s",
                           (flight[2]))
            seat = cursor.fetchone()[0]
            if ticket_sold == seat:
                price = 'Sold Out'
            elif ticket_sold / seat >= 0.7:
                price = int(
                    base_price *
                    1.2)  # when 70% of tickets are sold, raise the price
            else:
                price = base_price
            flight = [flight[1], flight[5], flight[6], price, flight[0]
                      ]  # airline, dept_time, arrv_time, price, flight_id
            n_flights.append(flight)
        # if comming back
        if request.form['trip'] == 'twoway':
            f_back_time = request.form['back_time']
            cursor.execute(
                "SELECT * from `flight` WHERE dept_airport= %s AND arrv_airport = %s and DATE(dept_time) = %s",
                (f_arrv_airport, f_dept_airport, f_back_time))
            b_flights = cursor.fetchall(
            )  # all the planes that matches the result
            b_n_flights = []
            for b_flight in b_flights:
                b_flight = list(b_flight)
                base_price = b_flight[3]
                # find out how many tickets are sold
                cursor.execute("SELECT * FROM ticket WHERE flight_id = %s",
                               b_flight[0])
                ticket_sold = len(cursor.fetchall())
                # find out how many seats are available
                cursor.execute(
                    "SELECT seat FROM airplane where airplane_id = %s",
                    (flight[2]))
                seat = cursor.fetchone()[0]
                if ticket_sold == seat:
                    price = 'Sold Out'
                elif ticket_sold / seat >= 0.7:
                    price = int(
                        base_price *
                        1.2)  # when 70% of tickets are sold, raise the price
                else:
                    price = base_price
                b_flight = [
                    b_flight[1], b_flight[5], b_flight[6], price, b_flight[0]
                ]  # airline, dept_time, arrv_time, price, flight_id
                b_n_flights.append(flight)
    return render_template('b/search.html',
                           dept_airport=dept_airport,
                           arrv_airport=arrv_airport,
                           result=n_flights,
                           back=b_n_flights)
Esempio n. 11
0
def confirm_order():
    """
    Confirm order
    
    Args:
        None
    
    Returns:
        Customer index page
    """
    db = get_db()
    cursor = db.cursor()
    # check ticket price

    if request.form['type'] == 'search':
        g.flight_id = request.form['flight_id']
        cursor.execute("SELECT * FROM flight WHERE flight_id = %s",
                       (g.flight_id, ))
        flight = list(cursor.fetchone())
        base_price = flight[3]
        # find out how many tickets are sold
        cursor.execute("SELECT * FROM ticket WHERE flight_id = %s", flight[0])
        ticket_sold = len(cursor.fetchall())
        # find out how many seats are available
        cursor.execute("SELECT seat FROM airplane where airplane_id = %s",
                       (flight[2]))
        seat = cursor.fetchone()[0]
        if ticket_sold / seat >= 0.7:
            price = int(base_price *
                        1.2)  # when 70% of tickets are sold, raise the price
        else:
            price = base_price
            result = [
                flight[1], flight[7], flight[5], flight[8], flight[6], price,
                flight[0]
            ]

    elif request.form['type'] == 'confirm':
        error = None
        customer_email = request.form['customer_email']
        flight_id = request.form['flight_id']
        payment = request.form['payment']
        card_number = request.form['card_number']
        name_on_card = request.form['name_on_card']
        exp_date = request.form['exp_date']
        pwd = request.form['pwd']
        cursor.execute("SELECT * FROM flight WHERE flight_id = %s",
                       (flight_id, ))
        flight = cursor.fetchone()
        base_price = flight[3]
        # find out how many tickets are sold
        cursor.execute("SELECT * FROM ticket WHERE flight_id = %s", flight[0])
        ticket_sold = len(cursor.fetchall())
        # find out how many seats are available
        cursor.execute("SELECT seat FROM airplane where airplane_id = %s",
                       (flight[2]))
        seat = cursor.fetchone()[0]
        if ticket_sold / seat >= 0.7:
            price = int(base_price *
                        1.2)  # when 70% of tickets are sold, raise the price
        else:
            price = base_price
        result = [
            flight[1], flight[7], flight[5], flight[8], flight[6], price,
            flight[0]
        ]
        if not check_password_hash(g.user[1], pwd):
            error = "Sorry, wrong password"
        cursor.execute("SELECT * FROM customer WHERE email = %s",
                       (customer_email))
        if not cursor.fetchone():
            error = "Can't find this user"
        if error is None:
            try:
                cursor.execute(
                    "INSERT INTO ticket (flight_id, airline, customer_email, sold_price, payment_method, card_number, name_on_card, expiration_date, purchase_date_time, BAID) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,CURTIME(), %s)",
                    (flight[0], flight[1], customer_email, price, payment,
                     card_number, name_on_card, exp_date, g.BAID))
                cursor.execute("SELECT * FROM ticket WHERE flight_id = %s",
                               flight[0])
                ticket_sold = len(cursor.fetchall())
                # find out how many seats are available
                cursor.execute(
                    "SELECT seat FROM airplane where airplane_id = %s",
                    (flight[2]))
                seat = cursor.fetchone()[0]
                if seat < ticket_sold:
                    db.rollback()
                    error = "Sorry, the ticket sold out."
                else:
                    db.commit()
                    return redirect(url_for('b.purchase_success'))
            except pymysql.Error as e:
                error = e
        flash(error)
    return render_template('b/confirm_order.html', result=result)
Esempio n. 12
0
def search():
    """
    Return Customer search flight page.

    Args:
        None

    Returns:
        Customer index page
    """
    # initialize the search result to be empty
    n_flights = 'n'  # n for null
    b_n_flights = 'o'  # stands for one way
    db = get_db()
    cursor = db.cursor()
    # cursor.execute("SELECT distinct dept_airport from flight")
    # dept_airport = cursor.fetchall()
    # cursor.execute("SELECT distinct arrv_airport from flight")
    cursor.execute("SELECT name FROM airport")
    dept_airport = arrv_airport = cursor.fetchall()
    if request.method == "POST":  # from search form submit

        f_dept_airport = request.form['dept_airport']  # search form names
        f_dept_time = request.form['dept_time']

        f_arrv_airport = request.form['arrv_airport']
        cursor.execute("SELECT * from `flight` WHERE dept_airport= %s AND arrv_airport = %s and DATE(dept_time) = %s",
                       (f_dept_airport, f_arrv_airport, f_dept_time))
        flights = cursor.fetchall()  # all the planes that matches the result
        n_flights = []
        if flights:
            for flight in flights:
                flight = list(flight)
                base_price = flight[3]
                # find out how many tickets are sold
                cursor.execute(
                    "SELECT * FROM ticket WHERE flight_id = %s", flight[0])
                ticket_sold = len(cursor.fetchall())
                # find out how many seats are available
                cursor.execute(
                    "SELECT seat FROM airplane where airplane_id = %s", (flight[2]))
                seat = cursor.fetchone()[0]
                if ticket_sold == seat:
                    price = 'Sold Out'
                elif ticket_sold / seat >= 0.7:
                    # when 70% of tickets are sold, raise the price
                    price = int(base_price * 1.2)
                else:
                    price = base_price
                # airline, dept_time, arrv_time, price, flight_id
                flight = [flight[1], flight[5], flight[6], price, flight[0]]
                n_flights.append(flight)
        else:
            n_flights = 'e'  # e for empty
        # if comming back
        if request.form['trip'] == 'twoway':
            f_back_date = request.form['back_date']
            cursor.execute("SELECT * from `flight` WHERE dept_airport= %s AND arrv_airport = %s and DATE(dept_time) = %s",
                           (f_arrv_airport, f_dept_airport, f_back_date))
            b_flights = cursor.fetchall()  # all the planes that matches the result
            b_n_flights = []
            if b_flights:
                for b_flight in b_flights:
                    b_flight = list(b_flight)
                    base_price = b_flight[3]
                    # find out how many tickets are sold
                    cursor.execute(
                        "SELECT * FROM ticket WHERE flight_id = %s", b_flight[0])
                    ticket_sold = len(cursor.fetchall())
                    # find out how many seats are available
                    cursor.execute(
                        "SELECT seat FROM airplane where airplane_id = %s", (flight[2]))
                    seat = cursor.fetchone()[0]
                    if ticket_sold == seat:
                        price = 'Sold Out'
                    elif ticket_sold / seat >= 0.7:
                        # when 70% of tickets are sold, raise the price
                        price = int(base_price * 1.2)
                    else:
                        price = base_price
                    # airline, dept_time, arrv_time, price, flight_id
                    b_flight = [b_flight[1], b_flight[5],
                                b_flight[6], price, b_flight[0]]
                    b_n_flights.append(flight)
            else:
                b = 'e'
    return render_template('c/search.html', dept_airport=dept_airport, arrv_airport=arrv_airport, result=n_flights, back=b_n_flights)
Esempio n. 13
0
def register(role):
    """
    Register in the system. Based on different roles in the system, return
    different register page.

    Args:
        role: Role of the user. Default is user.

    Returns:
        If requested by get, return rendered register page.
        If requested by post, redirect to reg_confirm page if registered successfully,
        else return error msg.
    """
    error = None
    db = get_db()
    cursor = db.cursor()
    # from register form submit, verify if register is successful.
    if request.method == "POST":
        # by default, Booking Agent ID is some random content.
        BAID = 'success'

        # Airline Staff Register
        if role == 'a':  # a for Airline Staff
            username = request.form['username']
            password = request.form['password']
            password_c = request.form['password_c']
            fname = request.form['fname']  # first name
            lname = request.form['lname']  # last name
            bday = request.form['bday']  # birthday
            airline = request.form['airline']  # airline name
            phone = request.form['phone']
            # query database to check if the username is used
            cursor.execute("SELECT * from `staff` WHERE `username` = %s",
                           (username, ))
            if not username:
                error = 'Username is required'
            elif not password:
                error = 'Password is required'
            elif password != password_c:
                error = 'Passwords do not match.'
            elif not fname:
                error = 'First name is required'
            elif not lname:
                error = 'Last name is required'
            elif not bday:
                error = 'Date of birth is required'
            elif not phone:
                error = "Phone number is required"
            elif cursor.fetchone() is not None:
                error = 'Airline Staff {} already exists.'.format(username)
            elif error is None:
                try:
                    cursor.execute(
                        "INSERT INTO staff (username, pwd, first_name, last_name, date_of_birth, airline) values(%s,%s,%s,%s,%s,%s)",
                        (username, generate_password_hash(password), fname,
                         lname, bday, airline))
                    db.commit()
                    cursor.execute(
                        'INSERT INTO staff_phone (phone_number, username) values (%s,%s)',
                        (phone, username))
                    db.commit()
                    return redirect(
                        url_for('auth.register_confirm', role=role, BAID=BAID))
                except pymysql.Error as e:
                    db.rollback()  # if register not successful then rollback
                    error = e.args[1]
            flash(error)

        # Booking Agent Register
        elif role == 'b':  # b for Booking Agent
            f_email = request.form['email']
            password = request.form['password']
            password_c = request.form['password_c']
            f_BAID = request.form["BAID"]
            cursor.execute('SELECT email FROM booking_agent WHERE email = %s',
                           (f_email, ))
            email = cursor.fetchone()
            cursor.execute("SELECT * FROM booking_agent WHERE BAID = %s",
                           (f_BAID, ))
            BAID = cursor.fetchone()
            if not f_email:
                error = "Email is required."
            elif not password:
                error = "Password is required."
            elif password_c != password:
                error = "Passwords do not match."
            elif email is not None:
                error = "Email is already used."
            elif len(f_BAID) > 8:
                error = "Booking Agent ID too long."
            elif BAID is not None:
                error = "Booking Agent ID is used."
            elif error is None:
                try:
                    cursor.execute(
                        "INSERT INTO booking_agent (email, pwd, BAID) values (%s,%s,%s)",
                        (f_email, generate_password_hash(password), f_BAID))
                    db.commit()
                    return redirect(
                        url_for('auth.register_confirm',
                                role=role,
                                BAID=f_BAID))

                except pymysql.Error as e:
                    db.rollback()
                    error = 'DBError'
                    flash(e)
            flash(error)

        # Customer Register.
        elif role == 'c':
            username = request.form['username']
            email = request.form['email']
            password = request.form['password']
            password_c = request.form['password_c']
            building = request.form['building']
            street = request.form['street']
            city = request.form['city']
            state = request.form['state']
            phone = request.form['phone']
            passport = request.form['passport']
            # Passport Expiration Date
            passport_exp = request.form['passport_exp']
            passport_country = request.form['passport_country']
            bday = request.form['bday']  # Date of birth
            cursor.execute('SELECT * FROM customer where email = %s', email)
            if not username:
                error = "Username is required"
            elif not email:
                error = "Email is required"
            elif not password:
                error = "Password is required"
            elif password != password_c:
                error = "Passwords do not match"
            elif not building:
                error = "Building is required"
            elif not street:
                error = "Street is required"
            elif not city:
                error = "City is required"
            elif not state:
                error = "State is required"
            elif not passport:
                error = "Passport is required"
            elif not passport_exp:
                error = "Passport expiration date is required"
            elif not passport_country:
                error = "Passport Country is required"
            elif not phone:
                error = "Phone is required"
            elif not bday:
                error = "Date of birth is required"
            elif cursor.fetchone() is not None:
                error = "This Email is already registered."
            elif error is None:
                try:
                    cursor.execute(
                        "INSERT INTO customer (email, name, pwd, building_number, street, city, state, passport_number, passport_expiration_date, passport_country, date_of_birth) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                        (email, username, generate_password_hash(password),
                         building, street, city, state, passport, passport_exp,
                         passport_country, bday))
                    db.commit()
                    cursor.execute(
                        "INSERT INTO customer_phone (phone, email) values (%s, %s)",
                        (phone, email))
                    db.commit()
                    return redirect(
                        url_for('auth.register_confirm', role=role, BAID=BAID))
                except pymysql.Error as e:
                    db.rollback()
                    error = e.args[1]
            flash(error)
            # redirect(url_for('auth.login'), role = role)

    if role == 'a':  # fetch all airline names if visiting airline staff registration page
        cursor.execute("SELECT * from airline")
        airlines = cursor.fetchall()
        return render_template('a/reg_a.html',
                               error=error,
                               role=role,
                               airlines=airlines)
    # Booking Agent & Customer Login
    return render_template('{}/reg_{}.html'.format(role, role),
                           error=error,
                           role=role)
Esempio n. 14
0
def login(role):
    """
    Login function depending on roles.

    Args:
        role: role.

    Returns:
        Redirect to index if login successful. Error message otherwise.
    """
    if request.method == 'POST':
        # requested by POST
        error = None
        db = get_db()
        cursor = db.cursor()
        # airline staff
        if role == 'a':
            username = request.form['username']
            password = request.form['password']
            cursor.execute('SELECT * from staff WHERE username = %s',
                           (username, ))  # Fetch user info
            user = cursor.fetchone()
            if user is None:
                error = "Incorrect Username"
            elif not check_password_hash(user[1], password):
                error = "Incorrect Password"

            if error is None:
                session.clear()
                session['role'] = 'a'
                session['username'] = username
                return redirect(url_for('a.index'))

            flash(error)
            return render_template('a/login_a.html')

        # booking agent
        if role == 'b':
            email = request.form['email']
            BAID = request.form['BAID']
            password = request.form['password']
            cursor.execute('SELECT * FROM booking_agent WHERE BAID = %s',
                           (BAID, ))
            user = cursor.fetchone()
            if user is None:
                error = "Incorrect BAID"
            elif user[0] != email:
                error = "Incorrect Email"
            elif not check_password_hash(user[1], password):
                error = "Incorrect Password"

            if error is None:
                session.clear()
                session['BAID'] = BAID
                session['role'] = 'b'
                return redirect(url_for('b.index'))

            flash(error)
            return render_template('b/login_b.html')

        # customer
        if role == 'c':
            email = request.form['email']
            password = request.form['password']
            cursor.execute("SELECT * FROM customer WHERE email = %s",
                           (email, ))
            user = cursor.fetchone()
            if user is None:
                error = 'Incorrect Email'
            elif not check_password_hash(user[2], password):
                error = 'Incorrect Password'
            if error is None:
                session.clear()
                session['email'] = email
                session['role'] = 'c'
                return redirect(url_for('c.index'))
            flash(error)
            return render_template('c/login_c.html')

    # Requested by GET, the user is trying to login
    if role == 'a':
        return render_template('a/login_a.html')
    if role == 'b':
        return render_template('b/login_b.html')
    if role == 'c':
        return render_template('c/login_c.html')