Beispiel #1
0
def signup():
    if request.method == "POST":

        _student_id = request.form['student_id']
        _membership = request.form['membership']
        _pwd = request.form['password']

        _stored_pwd = get_attribute_from_member(client, _student_id,
                                                "password")
        membership_number = get_attribute_from_member(client, _student_id,
                                                      "membership")

        if _membership == membership_number and _stored_pwd != "":
            flash(
                "You have already signed up. Use your membership number as username to login!"
            )
            return redirect(url_for('login_api.login'))

        if _membership != membership_number:
            flash(
                "Sorry! Your membership number is invalid! Please check with IEEE Exco about "
                "your membership status or click on the links below to sign up for official membership!"
            )
            return render_template("signup.html")

        _hashedpwd = hash_password(_pwd)

        change_attribute_of_member(client, _student_id, "password", _hashedpwd)

        flash("You have been signed up successfully!"
              )  # show in the login message place
        return redirect(url_for('login_api.login'))

    else:
        return render_template("signup.html")
Beispiel #2
0
def login():
    if request.method == "POST":

        _usrname = request.form['username']
        _pwdword = request.form['password']

        if _usrname == "" or _pwdword == "":
            flash("Username or password is empty!")
            return redirect(url_for('login_api.login'))

        _stdid = attibutes_to_list(client, "student_id")

        if _usrname == "admin":
            if _pwdword == "1i1e2e3e2019":
                session['admin'] = True
                session['login'] = True
                session['name'] = 'admin'
                session['id'] = 'admin'
                session['member'] = 'admin'
                return redirect(url_for('admin_api.index'))
            else:
                flash("Wrong admin password! Entry not authorized!")
                return render_template('login.html')

        # invalid membership
        if _usrname not in _stdid:
            flash("Sorry! Seems like you haven't register for an account yet. Click 'Sign up' below to register first!")
            return redirect(url_for('login_api.login'))

        _end_date = get_attribute_from_member(client, _usrname, "end_date")
        _now = datetime.datetime.timestamp(datetime.datetime.now())
        _end = float(datetime.datetime.timestamp(datetime.datetime.strptime(_end_date, "%Y-%m-%d %H:%M:%S")))
        # expired membership
        if _end < _now:
            flash("Sorry! Seems like your membership has expired! Please renew and sign in using your new membership again!")
            return redirect(url_for('login_api.login'))

        _stored_pwd = get_attribute_from_member(client, _usrname, "password")

        # verify password
        if verify_password(_stored_pwd, _pwdword):
            session['name'] = get_attribute_from_member(client, _usrname, "name")
            session['member'] = get_attribute_from_member(client, _usrname, "membership")
            session['id'] = _usrname
            session['login'] = True
            session['admin'] = False

            return redirect(url_for('loan_api.loan'))
        else:
            flash("Wrong password. Please try again!")
            return redirect(url_for('login_api.login'))

    else:
        session['email'] = ""
        return render_template("login.html")
Beispiel #3
0
def loan_info(student_id):
    logged_in = is_login()
    if logged_in:
        if session['id'] == student_id:
            is_self = True
        else:
            is_self = False
        if is_self:
            has_expired = False
            expiry_dates = get_attributes_from_sub_coll(
                client, student_id, "expiry")
            now = datetime.datetime.now()

            for date in expiry_dates:
                if datetime.datetime.timestamp(
                        now) > datetime.datetime.timestamp(date):
                    has_expired = True
                    break

            info = get_loaning_status(client, student_id)
            name = get_attribute_from_member(client, student_id, 'name')
            return render_template('loan_info.html',
                                   info=info,
                                   name=name,
                                   expired=has_expired)
        else:
            flash(
                "You are trying to view other people's loan information. Please sign in your own account and try again!"
            )
            return redirect(url_for('login_api.login'))
    else:
        flash("Please login first!")
        return redirect(url_for('login_api.login'))
def forgot():
    if request.method == 'POST':
        stdid = request.form['student_id']
        email = request.form['email']

        if stdid == "" or email == "":
            flash("Please do not leave blank!", 'warn')
            return render_template('forgot.html')

        stored_pwd = get_attribute_from_member(client, stdid, "password")

        _object = {'id': stdid, 'pwd': stored_pwd}

        serialized = serializer.dumps(_object, "forgot-password")

        recovery_url = "https://ieeesutdweb.herokuapp.com/{}".format(
            serialized)
        recovery_msg = '''
        Hello,
        
        A request to reset your IEEE SUTD Loaning System account password was received. Click on the link below to reset your password and sign into your account.
        This link is valid for 10 minutes.
        
        {}
        
        You can safely disregard this email if you didn't request a password reset and your password will not be changed.
        
        Thanks.
        
        IEEE SUTD Student Branch
        IEEE Web Development Team
        
        Contact us: [email protected]
        [This is an auto-generated email. Please do not reply.]
        '''.format(recovery_url)

        status = send_email(recovery_msg, email)
        if status == -1:
            flash(
                "Email was not sent due to network issue. Please try again later!",
                'warn')
            return render_template('forgot.html')
        flash(
            "A recovery link has been sent to your email. The link will be expired in 10 minutes.",
            'success')
        return render_template('forgot.html')
    else:
        return render_template('forgot.html')
def members():
    if is_admin():
        member_list = create_members_dictionary(client)
        length = len(member_list)
        if member_list is None:
            flash("Failed to extract member information from Firebase!")
            return redirect(url_for('error_api.error'))
        if request.method == "POST":
            stdid = request.form['reset']
            stdname = get_attribute_from_member(client, stdid, 'name')
            if stdname == -1:
                flash(
                    "Unable to get member's name. Check log for more details. Source: get_attribute_from_member"
                )
                return redirect(url_for('error_api.error'))
            change_attribute_of_member(client, stdid, "limit", 5)
            loaned_items = get_attributes_from_sub_coll(client, stdid, "id")
            x = delete_sub_coll_x(client, stdid)
            if x == -1:
                flash("Unable to delete sub collection from user {}".format(
                    stdid))
                return redirect(url_for('error_api.error'))
            if not loaned_items == -1:
                for item_id in loaned_items:
                    y = delete_sub_doc(item_id, stdid)
                    if y == -1:
                        flash("Unable to delete {}'s record in item {}".format(
                            stdid, item_id))
                        return redirect(url_for('error_api.error'))
            flash(
                "Member {} {}'s limit has been reset!".format(stdid, stdname),
                'success')
            member_list = create_members_dictionary(client)
            length = len(member_list)
            return render_template('members.html',
                                   members=member_list,
                                   length=length)
        else:
            return render_template('members.html',
                                   members=member_list,
                                   length=length)
    else:
        flash("You are unauthorized!")
        return redirect(url_for('login_api.login'))
def validate_key(serial):
    """
    Key here is user's previous stored hashed password
    """
    try:
        result = serializer.loads(serial, salt='forgot-password', max_age=c.RECOVERY_LINK_MAX_AGE)
    except SignatureExpired:
        flash("Your recovery link has expired!", 'warn')
        return redirect(url_for('error_api.error'))

    _id = result['id']

    stored_key = get_attribute_from_member(client, _id, "password")

    key = result['pwd']

    if key == stored_key:
        session['reset'] = True
        return redirect(url_for('reset_api.reset'))
    else:
        flash("Invalid recovery link! We cannot verify you.", 'warn')
        return redirect(url_for('error_api.error'))
def member_info(student_id):
    if is_admin():
        info = get_loaning_status(client, student_id)
        name = get_attribute_from_member(client, student_id, 'name')

        has_expired = False
        expiry_dates = get_attributes_from_sub_coll(client, student_id,
                                                    "expiry")
        now = datetime.datetime.now()

        for date in expiry_dates:
            if datetime.datetime.timestamp(now) > datetime.datetime.timestamp(
                    date):
                has_expired = True
                break

        if request.method == "POST":

            try:
                remind_btn = request.form['remind']
            except:
                remind_btn = None

            try:
                return_one = request.form['return_one']
            except:
                return_one = None

            try:
                return_all = request.form['return_all']
            except:
                return_all = None

            if remind_btn is not None:

                expired_items_str = ""
                student_email = get_attribute_from_member(
                    client, student_id, "email")
                loaned_items = get_loaning_status(client, student_id)
                now = datetime.datetime.now()
                for item in loaned_items:
                    expiry = item['expiry']
                    if datetime.datetime.timestamp(
                            now) > datetime.datetime.timestamp(expiry):
                        expired_items_str += "Item: {} , Item ID: {} , Expiry Date: {}\n".format(
                            item['name'], item['id'], expiry)

                reminder_email = '''
                Dear {},
                
                You have expired item(s) that have yet to be returned!
                Please return them ASAP otherwise you will not be able to loan any more item.
                
                Your expire item is/are:
                
                {}
                
                Please make an arrangement with any of the exco members via Telegram or Email to return your item.
                
                Thank you for your understanding!
                
                IEEE SUTD Student Branch
                IEEE Web Development Team
                
                [This is an auto-generated email. Please do not reply.]
                '''.format(name, expired_items_str)
                send_email(reminder_email.encode('utf-8'), student_email)
                flash(
                    "Reminder email has been successfully sent to {}".format(
                        name), 'success')
                return render_template('member_info.html',
                                       info=info,
                                       name=name,
                                       expired=has_expired)

            elif return_one is not None:
                item_id = return_one
                old_quantity = get_attr_from_sub_doc_x(client, student_id,
                                                       item_id, "quantity")
                new_quantity = old_quantity - 1
                old_limit = get_attribute_from_member(client, student_id,
                                                      "limit")
                if new_quantity == 0:
                    a = delete_sub_doc(item_id, student_id)
                    b = delete_sub_coll_doc(client, student_id, item_id)
                    if a == -1 or b == -1:
                        flash(
                            "Unable to update sub collection loaned item quantity!"
                        )
                        return redirect(url_for('error_api.error'))
                else:
                    old_quantity_from_inventory = get_sub_attr_from_member(
                        item_id, student_id, "quantity")
                    new_quantity_from_inventory = old_quantity_from_inventory - 1
                    status = update_sub_coll_attribute(client, student_id,
                                                       item_id, "quantity",
                                                       new_quantity)
                    status_inventory = update_attr_sub_coll(
                        item_id, student_id, "quantity",
                        new_quantity_from_inventory)
                    if status == -1 or status_inventory == -1:
                        flash(
                            "Unable to update sub collection loaned item quantity!"
                        )
                        return redirect(url_for('error_api.error'))
                new_limit = old_limit + 1
                limit_update = change_attribute_of_member(
                    client, student_id, "limit", new_limit)
                if limit_update == -1:
                    flash("Failed to update member's limit.")
                    return redirect(url_for('error_api.error'))
                old_quantity_inventory = get_attribute_value(
                    item_id, "quantity")
                new_quantity_inventory = old_quantity_inventory + 1
                status_update = update_attribute_value(item_id, "quantity",
                                                       new_quantity_inventory)
                if status_update == -1:
                    flash(
                        "Failed to update quantity in the main inventory system."
                    )
                    return redirect(url_for('error_api.error'))
                info = get_loaning_status(client, student_id)
                return render_template('member_info.html',
                                       info=info,
                                       name=name,
                                       expired=has_expired)

            elif return_all is not None:
                item_id = return_all
                old_limit = get_attribute_from_member(client, student_id,
                                                      "limit")
                old_loaned_quantity = get_attr_from_sub_doc_x(
                    client, student_id, item_id, "quantity")
                old_quantity_inventory = get_attribute_value(
                    item_id, "quantity")
                new_quantity_inventory = old_quantity_inventory + old_loaned_quantity
                new_limit = old_limit + old_loaned_quantity
                limit_update = change_attribute_of_member(
                    client, student_id, "limit", new_limit)
                if limit_update == -1:
                    flash("Failed to update member's limit.")
                    return redirect(url_for('error_api.error'))
                status_update = update_attribute_value(item_id, "quantity",
                                                       new_quantity_inventory)
                status_delete = delete_sub_coll_doc(client, student_id,
                                                    item_id)
                status_delete_inventory = delete_sub_doc(item_id, student_id)
                if status_update == -1 or status_delete == -1 or status_delete_inventory == -1:
                    flash(
                        "Failed to update quantity in the main inventory system."
                    )
                    return redirect(url_for('error_api.error'))
                info = get_loaning_status(client, student_id)
                return render_template('member_info.html',
                                       info=info,
                                       name=name,
                                       expired=has_expired)
        else:
            return render_template('member_info.html',
                                   info=info,
                                   name=name,
                                   expired=has_expired)

    else:
        flash("You are unauthorized!")
        return redirect(url_for('login_api.login'))
Beispiel #8
0
def loan():
    logged_in = is_login()
    admin = is_admin()
    if logged_in:
        inventory = create_inventory_dictionary()
        session_name = session['name']
        student_id = session['id']

        if request.method == "POST":
            try:
                picked_id = request.form['select']
            except Exception as e:
                print("No selection is done!", e)
                flash("You have yet to select anything!")
                return render_template('loan.html',
                                       name=session_name,
                                       inventory=inventory,
                                       id=student_id,
                                       admin=admin)

            quantity = get_attribute_value(picked_id, "quantity")
            item_name = get_attribute_value(picked_id, "name")
            limits = get_attribute_from_member(client, student_id, "limit")
            expiry_dates = get_attributes_from_sub_coll(
                client, student_id, "expiry")
            now = datetime.datetime.now()

            for date in expiry_dates:
                if datetime.datetime.timestamp(
                        now) > datetime.datetime.timestamp(date):
                    flash(
                        "You have expired item(s). Please check your loan record and return the expired item before making a new loan!"
                    )
                    return redirect(url_for('confirm_api.confirm'))

            if limits == 0:
                flash(
                    "You have already loaned 5 items! You can't loan until you return them."
                )
                return redirect(url_for('confirm_api.confirm'))

            if quantity == 0:
                flash(
                    "You selected an item which is run out. Please select other items we have."
                )
                return redirect(url_for('confirm_api.confirm'))

            update_attribute_value(picked_id, "quantity", quantity - 1)
            change_attribute_of_member(client, student_id, "limit", limits - 1)

            # for inventory side
            is_exist = check_sub_doc_exist(picked_id, student_id)
            if is_exist:
                number = get_sub_attr_from_member(picked_id, student_id,
                                                  "quantity")
                if number == -1:
                    number = 0
            else:
                number = 0

            # for member side
            x_is_exist = check_sub_doc_exist_x(client, student_id, picked_id)
            if x_is_exist:
                x_number = get_attr_from_sub_doc_x(client, student_id,
                                                   picked_id, "quantity")
                if x_number == -1:
                    x_number = 0
            else:
                x_number = 0

            expiry = now + datetime.timedelta(days=30)

            student_email = get_attribute_from_member(client, student_id,
                                                      "email")
            std_name = get_attribute_from_member(client, student_id, "name")

            sub_object = {
                "student": student_id,
                "name": std_name,
                "email": student_email,
                "quantity": number + 1,
                "expiry": expiry
            }
            sub_object_2 = {
                "id": picked_id,
                "name": item_name,
                "quantity": x_number + 1,
                "expiry": expiry
            }
            inventory_updated = create_sub_collection(picked_id, "loaners",
                                                      student_id, sub_object)
            member_updated = create_sub_collection_member(
                client, student_id, "loaned_items", picked_id, sub_object_2)

            if inventory_updated == -1 or member_updated == -1:
                flash("Can't create sub collection!")
                return redirect(url_for('error_api.error'))

            new_quantity = get_attribute_value(picked_id, "quantity")
            new_limit = get_attribute_from_member(client, student_id, "limit")

            student_name = get_attribute_from_member(client, student_id,
                                                     "name")
            student_email = get_attribute_from_member(client, student_id,
                                                      "email")

            master_email = '''
            [Inventory System Update]
            --Item: {}
            --Item ID: {}
            --Quantity left: {}
            
            was loaned out successfully
            by
            
            --Student ID: {}
            --Studnet name: {}
            --Remaining loans: {}
            
            Item expiry date is set to be:
            {}
            '''.format(item_name, picked_id, new_quantity, student_id,
                       student_name, new_limit,
                       datetime.datetime.strftime(now, "%Y-%m-%d %H:%M:%S"))

            loaner_email = '''
            Thank you for using IEEE SUTD Student Branch online inventory loaning system.
            Here is a summary for your loaning status.
            
            --Loaned Item: {}
            --Item ID: {}
            --Expiry date: {}
            
            Please make an arrangement with any of the exco members via Telegram or Email to collect your item.
            
            For further query, please contact us at [email protected]
            Please remember to return your item before the expiry date.
            Thank you for your understanding!
            
            IEEE SUTD Student Branch
            IEEE Web Development Team
            
            [This is an auto-generated email. Please do not reply.]
            '''.format(item_name, picked_id,
                       datetime.datetime.strftime(now, "%Y-%m-%d %H:%M:%S"))

            send_email(master_email.encode('utf-8'), "*****@*****.**")
            sleep(1)
            send_email(loaner_email.encode('utf-8'), student_email)

            flash_message = "You picked {}. " \
                            "Now left {}. " \
                            "Remaining number of items you can loan: {}. " \
                            "Check your loaned item here".format(item_name, new_quantity, new_limit)
            flash(flash_message)
            return redirect(url_for('confirm_api.confirm'))
        else:
            return render_template('loan.html',
                                   name=session_name,
                                   inventory=inventory,
                                   id=student_id,
                                   admin=admin)
    else:
        flash("Please login first!")
        return redirect(url_for('login_api.login'))