Example #1
0
def sign_up():

    form = site_forms.Signup(request.form)
    if request.method == 'POST' and form.validate():

        name = thwart(form.username.data)
        email = thwart(form.email.data)
        password = thwart(form.password.data)
        re_password = thwart(form.confirm.data)
        company_name = thwart(form.company_name.data)

        if password == re_password:
            # TODO hash password
            password = crypt.encrypt(password)
            new_company = company.Company.enter_company_detail(company_name)
            user = member.Member.create_member(name, email, password, new_company.id, new_company.schema)

            session['company'] = new_company.id
            session['user'] = user.id
            return 'next page'
        else:
            flash('Passwords do not match', 'error')
            return render_template('sign_up/sign_up_form.html', form=form)

    return render_template('sign_up/sign_up_form.html', form=form)
Example #2
0
def login():
    form = UserLogin()

    if request.method == "POST":
        email = thwart(request.form["email"])
        password = thwart(request.form["password"])

        if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", email):
            if not check_new_user_email(email):
                user = get_user_id(email)

                check = comfirm_password(user[0], email, password)
                password = random.random()

                if check:
                    session["username"] = user[1]
                    session["userid"] = user[0]
                    session["logged_in"] = True
                    flash("Welcome back " + session["username"] + ".")
                    return redirect(url_for("index"))

                else:
                    flash("Please check your login details")
                    return redirect(url_for("login"))
            else:
                flash("Please check your login details")
                return redirect(url_for("login"))
        else:
            flash("Please check your login details")
            return redirect(url_for("login"))

    return render_template("users/login.html", form=form)
Example #3
0
def login_action(form):
    if request.method == 'POST' and form.validate():
        user = thwart(form.userEmail.data)
        password = thwart(form.password.data)

        system_data = sql_functions.get_possible_user_login_details(user)

        for value in system_data:
            if crypt.verify(password, value[1]):
                return value, True
Example #4
0
def set_company_details():
    """
    Sets up the new company for the user that has just made an account
    :return:
    """
    # TODO If the user makes account but try not set a company up they should be forced to do so.
    form = Set_up_company(request.form)

    if request.method == "POST" and form.validate():
        company = thwart(form.company_name.data)

        company_ID, company_schema = sql_functions.enter_company_detail(company)

        sql_functions.link_user_company(session["temp_user_details"][0], company_ID)

        login_details = {
            "user_ID": session["temp_user_details"][0],
            "company_ID": company_ID,
            "company_schema": company_schema,
            "person_ID": "",
        }

        session["login_details"] = login_details

        return redirect(url_for("confirm_user_setup_details"))

    return render_template("SetUp/setCompanyDetails.html", form=form)
Example #5
0
def create_job_page():
    """
    Code to make a job in the basic form is here
    :return:
    """
    form = siteForms.JobCreate(request.form)
    if request.method == "POST":
        title = thwart(form.name.data)
        description = thwart(form.description.data)
        cost = thwart(str(form.pCost.data))
        length = thwart(str(form.pTime.data))

        values = [title, description, cost, length]

        job_number = sql_functions.create_job(values, session["login_details"])
        session["temp_job_number"] = job_number

        return redirect(url_for("new_job_overview"))

    return render_template("private/jobs/create.html", form=form)
Example #6
0
def user_create():
    """
    The function lets a logged in user add more members to the company
    :return:
    """
    form = siteForms.CreateNewUser(request.form)
    user_name = sql_functions.get_sudo_username(session["login_details"])
    password = password_gen()

    if request.method == "POST" and form.validate():
        new_user_name = thwart(form.user_name.data)
        first_name = thwart(form.first_name.data)
        last_name = thwart(form.last_name.data)
        email = thwart(form.userEmail.data)

        information = (new_user_name, email, first_name, last_name, crypt.encrypt(password))

        if sql_functions.check_new_username(new_user_name, session["login_details"]):
            added_user = sql_functions.add_user(information, session["login_details"])
            return redirect(url_for("user_review", added_user=added_user))
        else:
            flash("User name and or email has been used before")

    return render_template("private/users/add.html", form=form, user_name=user_name, password=password)
Example #7
0
def signup():
    # fixme there is no way to roll back to this page if the company works wrong. Need a role back function on the database
    """
    This uses the new database layout and will sign a new user up with an account
    :return:
    """
    form = Signup(request.form)

    if request.method == "POST" and form.validate():
        sign_up_form = (
            thwart(form.user_name.data),
            thwart(form.userEmail.data),
            crypt.encrypt(thwart(form.password.data)),
            thwart(str(form.accept_terms.data)),
        )

        userID = sql_functions.sign_up_user(sign_up_form)
        session.clear()
        session["temp_user_details"] = (userID, sign_up_form[0])

        flash("You are now signed up")
        return redirect(url_for("set_company_details"))

    return render_template("SetUp/signup.html", form=form)
Example #8
0
def register():
    form = Create_User()
    if request.method == "POST":
        form_values = {
            "first_name": thwart(request.form["first_name"]),
            "surname": thwart(request.form["surname"]),
            "email": thwart(request.form["email"]),
            "password": sha256_crypt.encrypt(thwart(request.form["password"])),
            "account_type": int(thwart(str(32))),
            "join_date": int(thwart(str(int(time.time())))),
        }
        re_password = thwart(request.form["re_password"])

        if sha256_crypt.verify(re_password, form_values["password"]):
            re_password = random.random()

            if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", form_values["email"]):

                is_new = check_new_user_email(form_values["email"])

                if is_new:
                    create_user_account(form_values)
                    user = get_user_id(form_values["email"])
                    session["username"] = user[1]
                    session["userid"] = user[0]
                    session["logged_in"] = True

                    flash("Thank you, " + form_values["first_name"] + " for joining our family.")
                    return redirect(url_for("index"))
                else:
                    flash("It seems that email is already used.")
                    return redirect(url_for("register", form=form))
            else:
                flash("Please enter a valid email address")
                return redirect(url_for("register", form=form))
        else:
            flash("Your passwords did not match.")
            return redirect(url_for("register", form=form))

            # TODO: add in the sql function and the right redircts

    return render_template("users/register.html", form=form)
Example #9
0
def login():
    """Wysyła zapytanie do bazy danych o login użytkownika a następnie porównuje
	jego zhashowane hasło z hashem z bazy danych"""
    try:
        con, conn = connection()
        if request.method == "POST":
            con.execute("SELECT * FROM users WHERE username = (%s)",
                        thwart(request.form['username']))
            data = con.fetchone()['password']
            if sha256_crypt.verify(request.form['password'], data):
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash("JesteÅ› zalogowany jako  " + session['username'])

                return redirect(request.referrer)
            else:
                flash("Niepoprawne hasło")
        gc.collect()
        return redirect(request.referrer)
    except Exception:
        flash("Niepoprawna nazwa użytkowania")
        return redirect(request.referrer)
Example #10
0
def admin_check(c_name):
    c, conn = connection()
    u_name = thwart(c_name)
    admin_status = False

    try:
        data = c.execute("SELECT * FROM users WHERE username = %s", u_name, )
        user_rank = c.fetchone()[8]
        if user_rank >= 3:
            session['user_rank'] = '3'
            session['admin_status'] = True
            session.modified = True

            admin_status = True

    except Exception:
        admin_status = False

    c.close()
    conn.close()
    gc.collect()

    return admin_status
Example #11
0
def register_page():
    try:
        form = RegistrationForm(request.form)

        if request.method == "POST" and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))
            c, conn = connection()

            x = c.execute("SELECT * FROM users WHERE username = (%s)",
                          (thwart(username)))

            if int(x) > 0:
                error = "That username is already taken, please choose another"
                return render_template('register.html', form=form, error=error)

            else:
                c.execute(
                    "INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)",
                    (thwart(username), thwart(password), thwart(email),
                     thwart("translate")))
                response = rh.post("/group/" + thwart(username),
                                   {"uid": thwart(username)})
                conn.commit()
                flash("Thanks for registering!")
                c.close()
                conn.close()
                gc.collect()

                session['logged_in'] = True
                session['username'] = username

                return redirect(url_for('index'))

        return render_template("register.html", form=form)

    except Exception as e:
        return (str(e))
Example #12
0
def about():
    error = ""
    try:
        c, conn = connection()
        if request.method == "POST":

            data = c.execute(
                "SELECT * FROM users WHERE username = ('{0}')".format(
                    thwart(request.form['username'])))

            data = c.fetchone()[2]

            if sha256_crypt.verify(request.form["password"], data):
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash("You are now logged in " + session['username'] + "!")
                return redirect(url_for("message_page"))

            else:
                error = "Invalid creditials, try again."  # want this the same as below because then the hacker does not know what the error is.
        return render_template("about.html")
    except Exception as e:
        return render_template("500.html", error=e)
Example #13
0
def index():
    error = ""
    try:
        c, conn = connection()
        if request.method == "POST":
            data = c.execute("SELECT * FROM users WHERE username = ('{0}')".format(thwart(request.form['username'])))
            
            data = c.fetchone()[2]
            
            if sha256_crypt.verify(request.form["password"],data):
                session['logged_in'] =True
                session['username'] = request.form['username']
                
                flash("You are now logged in "+session['username']+"!")
                return redirect(url_for("dashboard"))
            else:
                error = "Invalid credentials, try again."
                
        return render_template("main.html", error = error)
    
    except Exception as e:
        flash(e) # remove for production
        error = "Invalid creditials, try again."
        return render_template("main.html", error = error)
Example #14
0
def report():
    try:
        if request.method == "POST":
            name = request.form["name"]
            latitude = request.form["latitude"]
            longitude = request.form["longitude"]
            mobile = request.form["mobile"]
            if name == "" or latitude == "" or longitude == "" or mobile == "":
                flash("Please fill corect data")
                return render_template('report.html')
            c, conn = cursor_conn()

            x = c.execute(
                "SELECT mobile FROM FLASKAPP.users WHERE username = (%s)",
                (thwart(session['username'])))
            usermobile = c.fetchone()['mobile']
            c.execute(
                "INSERT INTO FLASKAPP.victims (name, reporterMobile, mobile, latitude, longitude, status) VALUES (%s, %s, %s, %s, %s, %s)",
                (thwart(name), thwart(usermobile), thwart(mobile),
                 thwart(latitude), thwart(longitude), thwart("not_rescued")))

            conn.commit()
            flash("Person Added. Relief workers will find for your loved one!")
            c.close()
            conn.close()
            gc.collect()

            return redirect(url_for('report'))
        return render_template("report.html")

    except pymysql.IntegrityError as e:
        flash("Person has already been reported")
        return render_template('report.html')
    except Exception as e:
        flash("Please fill corect data")
        return render_template('report.html')
Example #15
0
def update_user_details(request, session, flash, send_mail_change):
    error = ''
    c, conn = dict_connection()
    min_date, max_date = get18_back()
    c.execute(
        "select * from ((user inner join userdetails on userdetails.userdetilsid = user.user_details)"
        "inner join address on address.Addressid=user.user_address) where username = '******'"
        .format(thwart(session['username'])))
    data_dict = c.fetchone()

    print(data_dict)

    class UpdateForm(Form):
        username = StringField('Username', render_kw={"readonly": ""})
        firstname = StringField('First Name', render_kw={"readonly": ""})
        lastname = StringField('Last Name', render_kw={"readonly": ""})
        email = StringField('Update Email Address', [validators.Email()])
        phonenumber = StringField('Update Phone Number',
                                  [validators.InputRequired()])
        date = DateField('Date Of Birth', [validators.InputRequired()],
                         render_kw={"readonly": ""})
        weight = IntegerField('Weight in kgs', [validators.InputRequired()],
                              render_kw={"placeholder": "50<yourWeight<150"})
        bloodgroup = StringField('Blood Group', render_kw={"readonly": ""})
        gender = StringField('Gender', render_kw={"readonly": ""})
        pdonations = IntegerField('Previous Donations',
                                  default=data_dict['previousdonations'])
        address = TextAreaField('Address', [validators.InputRequired()])
        state = SelectField('State or Union Teritorry',
                            [validators.InputRequired()],
                            coerce=str,
                            choices=states,
                            default=data_dict['State'])
        present_password = PasswordField('Present Password',
                                         [validators.InputRequired()])
        new_password = PasswordField(
            'Update Password',
            [validators.EqualTo('confirm', message="Passwords must match.")],
            render_kw={"placeholder": "Min-7, 1 Upper, 1 lower, 1 spec char"})
        confirm = PasswordField(
            'Repeat Password',
            render_kw={"placeholder": "Must be equal to previoius field"})

    form = UpdateForm(request.form)

    if request.method == "POST" and form.validate():
        print("yesoo")
        phonenumber = thwart(form.phonenumber.data)
        email = thwart(form.email.data)
        address = thwart(form.address.data)
        state = form.state.data

        weight = int(form.weight.data)
        pdonations = int(form.pdonations.data)
        city = thwart(request.form['city'])
        c.execute(
            "SELECT userpassword FROM user WHERE username = ('{0}')".format(
                data_dict['username']))
        data = c.fetchone()
        print(data['userpassword'])

        if sha256_crypt.verify(form.present_password.data,
                               data['userpassword']):
            print("yes it")
            if form.new_password.data:
                password = sha256_crypt.encrypt(str(form.new_password.data))
                c.execute(
                    "UPDATE user SET userpassword = '******' WHERE username = '******'"
                    .format(password, data_dict['username']))

            if email == data_dict['emailid']:
                pass
            else:
                print('camed ')
                link = gen_verify_link(session['username'], email)
                send_mail_change(session['username'], email, link)
                flash(
                    "Please verify your changed mail id by the verification link  sent to your new mail id"
                )
                c.execute(
                    "UPDATE user SET email_verification_link = '{0}', emailid = '{1}', emailconfirm = 0 WHERE username = '******'"
                    .format(link, email, data_dict['username']))

            c.execute(
                "UPDATE user SET phonenumber = '{0}' WHERE username = '******'".
                format(phonenumber, data_dict['username']))
            c.execute(
                "UPDATE address SET city='{0}', state='{1}', address='{2}' WHERE Addressid = '{3}'"
                .format(city, state, address, data_dict['Addressid']))
            c.execute(
                "UPDATE userdetails SET previousdonations = '{0}', weight = '{1}' WHERE userdetilsid='{2}'"
                .format(pdonations, weight, data_dict['userdetilsid']))

            flash("Details Updated Successfully")
            conn.commit()
            c.close()
            conn.close()
            return 0, '', form, min_date, max_date, data_dict
        else:
            error = 'Wrong password, please try again.'
    return 1, error, form, min_date, max_date, data_dict
Example #16
0
def registration(request, RegistrationForm, flash, session,
                 send_verification_mail):
    c, conn = connection()
    min_date, max_date = get18_back()

    form = RegistrationForm(request.form)

    print("yesno")

    if request.method == "POST" and form.validate():
        print("yesoo")
        username = thwart(form.username.data)
        firstname = thwart(form.firstname.data)
        lastname = thwart(form.lastname.data)
        phonenumber = thwart(form.phonenumber.data)
        email = thwart(form.email.data)
        address = thwart(form.address.data)
        # city = thwart(form.city.data)
        state = form.state.data
        # country = thwart(form.country.data)
        gender = thwart(form.gender.data)
        date = str(form.date.data)
        age = send_to_find_age(date)
        weight = int(form.weight.data)
        bloodgroup = form.bloodgroup.data
        pdonations = int(form.pdonations.data)
        password = sha256_crypt.encrypt(str(form.password.data))
        city = thwart(request.form['city'])
        x = c.execute("SELECT * FROM user WHERE username = ('{0}')".format(
            thwart(username)))
        print("yesit")
        if int(x) > 0:
            flash("That username is already taken, please choose another")
            return 1, form, max_date, min_date
            # return render_template('register.html', form=form, cities_dict=cities_dict, min_date=min_date, max_date=max_date)
        else:
            link = gen_verify_link(username, email)
            c.execute(
                "INSERT INTO address(Address, City, State ) VALUES ('{0}','{1}','{2}')"
                .format(address, city, state))
            c.execute("SELECT @last1 := LAST_INSERT_ID()")
            c.execute(
                "INSERT INTO userdetails(DateofBirth, Age, weight, gender, BloodGroup, previousdonations) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')"
                .format(date, age, weight, gender, bloodgroup, pdonations))
            c.execute("SELECT @last2 := LAST_INSERT_ID()")
            c.execute(
                "INSERT INTO user (username, firstname, lastname, userpassword, phonenumber, emailid, email_verification_link, user_address,user_details) VALUES ( %s, %s, %s, %s, %s, %s, %s,  @last1,@last2)",
                (username, firstname, lastname, password, phonenumber, email,
                 link))
            conn.commit()
            # c.execute("INSERT INTO user (username,userpassword, emailid, email_verification_link) VALUES (%s, %s, %s, %s)", (thwart(username), thwart(password), thwart(email), link))
            # conn.commit()
            # c.execute("SELECT @last:=LAST_INSERT_ID")
            send_verification_mail(thwart(username), thwart(email), link)

            flash(
                "Thanks for registering, please verify your email id from the mail sent to your mail id!"
            )

            c.close()
            conn.close()
            session['logged_in'] = True
            session['username'] = username
            return 0, form, max_date, min_date
    return 1, form, max_date, min_date
Example #17
0
def client_create():
    """
    This page will add a client company to the user company and will redirect to view the clients home page.
    :return:
    """
    form = ClientCompany(request.form)

    if request.method == "POST" and form.validate():
        values = {}
        values["address"] = []
        values["comm"] = []
        values["name"] = thwart(form.company_name.data)
        values["code"] = thwart(form.sort_code.data)
        values["phone"] = thwart(form.company_phone.data)
        values["address"].append(
            {
                "line_1": thwart(form.address_line1.data),
                "line_2": thwart(form.address_line2.data),
                "city": thwart(form.address_town.data),
                "county": thwart(form.address_county.data),
                "country": thwart(form.address_country.data),
                "postcode": thwart(form.address_postcode.data),
                "billing": 1,
                "default": 1,
            }
        )

        values["comm"].append({"detail": thwart(form.company_email.data), "main": 1, "type": "email"})
        values["comm"].append({"detail": thwart(form.company_phone.data), "main": 1, "type": "phone"})

        client = site_actions.ClientCompany.create_client(values, session["login_details"])
        client.add_address(address_list=values["address"])
        client.add_communication(values=values["comm"])

        flash(client.name)

        return redirect(url_for("private_home"))
    return render_template("/private/client/create.html", form=form)
Example #18
0
def criminalinfo():
    if 'auth' in session:
        try:
            c, conn = connection()
            if request.method == "POST":
                name = request.form['name']
                nic = request.form['nic']
                age = request.form['age']
                add01 = request.form['add01']
                add02 = request.form['add02']
                add03 = request.form['add03']
                eye = request.form['eye']
                hair = request.form['hair']
                gender = request.form['gender']

                data = c.execute("SELECT * FROM  criminalinfo WHERE nic=(%s)", (thwart(nic)))

                if int(data) > 0:
                    print(data)
                else:

                    c.execute(
                        "INSERT INTO  criminalinfo (nic,name,age,addressline01,addressline02,addressline03,eyecolor,haircolor,gender) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                        (thwart(nic), thwart(name), thwart(age), thwart(add01), thwart(add02), thwart(add03), thwart(eye),
                         thwart(hair), thwart(gender)))
                    conn.commit()
                    c.close()
                    conn.close()
                    target = os.path.join(APP_ROOT, 'uploads/train/' + nic)
                    print(target)
                    if not os.path.isdir(target):
                        os.mkdir(target)

                    count = 0
                    for file in request.files.getlist('img'):
                        print(file)
                        count = count + 1
                        filename = file.filename
                        print(filename)
                        destination = "/".join([target, filename])
                        print(destination)
                        file.save(destination)

                    # ttt
                    obj = preprocesses(TRAIN_FOLDER, PRE_FOLDER)
                    nrof_images_total, nrof_successfully_aligned = obj.collect_data()

                    print('Total number of images: %d' % nrof_images_total)
                    print('Number of successfully aligned images: %d' % nrof_successfully_aligned)

                    print("Training Start")
                    obj = training(PRE_FOLDER, MODEL_DIR, CLASSIFIER)
                    get_file = obj.main_train()
                    print('Saved classifier model to file "%s"' % get_file)

                    # flash('User registeration succeeded please log in', 's_msg')
                    return jsonify(success=["User Registration Success"], value=True)


        except Exception as e:
            return (str(e))
            print(e)

    else:
        return render_template("login.html", data="please log in")
    return render_template("criminalinfo.html")
Example #19
0
def make_dashboard(form, request, flash, session):
    try:
        try:
            if 'logged_in' not in session:
                flash("Welcome Guest!")
            print("niced")

            if request.method == 'POST' and form.validate():
                blood_receive_dict = who_can_donate()
                print("veryniced")
                c, conn = connection()
                blood_group = form.bloodgroup.data
                city = request.form['city']
                state = form.state.data
                data_user_list = []
                c.execute(
                    "select firstname, lastname, phonenumber, emailid, Address, uid from (select user.username, user.firstname, user.lastname, user.phonenumber, user.emailid, user.uid, address.city, address.state, address.Address, userdetails.BloodGroup from ((user inner join address on user.user_address = address.Addressid) inner join userdetails on user.user_details = userdetails.userdetilsid)) as t where Bloodgroup = '{0}' and state = '{1}' and city = '{2}' and username != '{3}' "
                    .format(blood_group, state, city,
                            thwart(session['username'])))
                data_user_list = c.fetchall()
                print(data_user_list)
                print(blood_receive_dict)
                data_list = ()
                for i in blood_receive_dict[blood_group]:
                    c.execute(
                        "select firstname, lastname, phonenumber, emailid, Address, uid  from (select user.username, user.firstname, user.lastname, user.phonenumber, user.emailid, user.uid, address.city, address.state, address.Address, userdetails.BloodGroup from ((user inner join address on user.user_address = address.Addressid) inner join userdetails on user.user_details = userdetails.userdetilsid)) as t where Bloodgroup = '{0}' and state = '{1}' and city = '{2}' and username != '{3}' "
                        .format(i, state, city, thwart(session['username'])))
                    temp_list = c.fetchall()
                    for j in temp_list:
                        data_list = data_list + (j, )
                print(data_list)
                c.close()
                print("veryveryniced")
                # return render_template("find_donors.html", user_list=data_list, city=city, state=state, blood_group=blood_group)
                return 0, data_list, city, state, blood_group, '', ''
            c, conn = connection()
            print("good")
            c.execute("select uid from user where username = '******'".format(
                thwart(session['username'])))
            user_id = c.fetchone()
            c.close()
            print("ggood")
            c, conn = dict_connection()
            # c.execute("select Notification_data.notification from Notifications_data inner join Notiwhere user_id = '{0}'".format(user_id[0]))
            c.execute(
                "select notification, created_by, subject from Notification_data inner join Notification_users on  id= Notification_users.notification_id where to_user='******'"
                .format(user_id[0]))

            notifications = c.fetchall()
            names = []
            for i in notifications:
                names.append(get_name(i['created_by']))
            c.close()
            print(names)
            print(notifications)

            print("notnice")
        except Exception as e:
            flash(e)
        return 1, '', '', '', '', notifications, names
    except Exception as e:
        return 2, '', '', '', '', '', ''
Example #20
0
def register_page():
    try:
        form = RegistrationForm(request.form)

        if form.validate_on_submit():
            username = form.username.data
            name = form.name.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))
            c, conn = connection()
            try:
                x = c.execute("SELECT * FROM users WHERE username = (%s)",
                              (thwart(username)))
            except pymysql.Error as e:
                return ("Failure checking for previous user %d: %s" %
                        (e.args[0], e.args[1]))

            if int(x) > 0:
                flash("That username is already taken, please choose another")
                return render_template('register.html', form=form)

            else:
                try:
                    x = c.execute(
                        "INSERT INTO users (username, goes_by_name, password, email, tracking) VALUES (%s, %s, %s, %s, %s)",
                        (thwart(username), thwart(name), thwart(password),
                         thwart(email),
                         thwart("/introduction-to-python-programming/")))
                    conn.commit()
                except pymysql.Error as e:
                    return ("Failure inserting new user %d: %s" %
                            (e.args[0], e.args[1]))

                flash("Thanks for registering!")
                c.close()
                conn.close()
                gc.collect()

                session['logged_in'] = True
                session['username'] = username
                session['last_active'] = int(time.time())

                return redirect(url_for('dashboard'))

        return render_template("register.html", form=form)
    except AssertionError:
        """
        _, _, tb = sys.exc_info()
        traceback.print_tb(tb) # Fixed format
        tb_info = traceback.extract_tb(tb)
        filename, line, func, text = tb_info[-1]
    
        return('An error occurred on line {} in statement {}'.format(line, text))
        """
        app.logger.error('An error occurred on line {} in statement {}'.format(
            line, text))
        return ("An error occurred during signup.")

    except Exception as e:
        rtn = "<p>Attr:</p>"
        for attr in dir(e):
            rtn = rtn + "<p>" + attr + "</p>"
        return (repr(e))
Example #21
0
def add_endpoint():
    try:
        form = AddEndpointForm(request.form)

        if request.method == "POST":
            c, conn = connection()

            endpoint_name = form.endpoint_name.data
            hostname = form.hostname.data
            ip_addr = form.ip_addr.data
            zip_code = form.zip_code.data
            check_type = form.check_type.data
            check_interval = form.check_interval.data
            c_enabled = 1
            cc_time = time.strftime("%H:%M:%S %m-%d-%Y")

            x = c.execute("SELECT * FROM endpoints WHERE hostname = %s", (hostname,))
            print(f"Hostname used is :'{hostname}'")

            if int(x) > 0:
                print(x)
                flash(f"{endpoint_name.capitalize()} is already in the system.")
                return render_template("add_endpoint.html", form=form)

            else:
                c.execute(
                    "INSERT INTO endpoints (endpoint_name, \
                                            hostname, \
                                            ip, \
                                            zip, \
                                            check_type, \
                                            enabled, \
                                            check_interval, \
                                            last_check, \
                                            next_check, \
                                            enabled_date, \
                                            creation_date) \
                                            VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                    (thwart(endpoint_name),
                     thwart(hostname),
                     thwart(ip_addr),
                     thwart(zip_code),
                     thwart(check_type),
                     c_enabled,
                     check_interval,
                     cc_time,
                     cc_time,
                     cc_time,
                     cc_time))
                conn.commit()

            flash(f"{endpoint_name.capitalize()} has been added!")

            return redirect(url_for('monitor'))

        return render_template("add_endpoint.html", form=form)

    except Exception as e:
        if netpop_logging_to_console:
            app.logger.error(e)

        return render_template("error.html", error=e)