Ejemplo n.º 1
0
def hello():
    pw_hash = bcrypt.generate_password_hash(request.form['password'])
    pwtest = request.form['password']
    swtest = request.form['conpassword']
    teststr = request.form['firstname']
    lastname = request.form['lastname']
    if not teststr.isalpha() or not lastname.isalpha():
        flash("Names must be all alphanumeric characters.")
    elif len(teststr) < 2 or len(lastname) < 2:
        flash("Names must longer than two characters.")
    elif request.form['password'] != request.form['conpassword']:
        flash("Password must match.")
    elif len(swtest) < 8 or len(pwtest) < 8:
        flash("Password must be at least eight characters")
    elif not EMAIL_REGEX.match(request.form['email']):
        flash("Invalid email address.")

    else:
        flash("Registration successfully completed")
        query = "INSERT INTO users (fname, lname, email, hpwd) VALUES (%(f)s, %(l)s, %(e)s, %(h)s);"
        data = {
            'f': request.form['firstname'],
            'l': request.form['lastname'],
            'e': request.form['email'],
            'h': pw_hash
        }
        db = MySQLConnection('login')
        insert = db.query_db(query, data)
        print(data)
        return render_template('welcome.html')
    return render_template('registration.html')
Ejemplo n.º 2
0
def index_post():
    print("post /")
    mysql = MySQLConnection('mydb')

    name = request.form["name"]
    location = request.form["location"]
    language = request.form["language"]
    comment = request.form.get("comment", str())

    data = dict(name=name, location=location, language=language)
    if comment:
        print("yes comment")
        data["comment"] = comment
        comment_column = ", comment"
        comment_parameter = ", %(comment)s"
    else:
        print("no comment")
        comment_column = str()
        comment_parameter = str()

    query = f"INSERT INTO dojo_survey(name, location, language{comment_column}) " \
        f"VALUES (%(name)s, %(location)s, %(language)s{comment_parameter});"

    comment_id = mysql.query_db(query, data)
    session["comment_id"] = comment_id
    session["location"] = location
    session["language"] = language
    session["comment"] = comment

    return redirect(url_for('result'))
Ejemplo n.º 3
0
def register():
    first_name = request.form['first_name']
    last_name = request.form['last_name']
    email = request.form['email']

    if not (first_name and last_name and email):
        flash("Our form validation failed!", "error")
        return redirect("index.html")

    password = request.form['password']
    password_hash = b_crypt.generate_password_hash(password)

    mysql = MySQLConnection("mydb")
    query = "INSERT into peak_user(first_name, last_name, email, password_hash) " \
            "VALUES (%(first_name)s, %(last_name)s, %(email)s, %(password_hash)s)"
    data = dict(first_name=first_name,
                last_name=last_name,
                email=email,
                password_hash=password_hash)
    r = mysql.query_db(query, data)
    if r is False:
        flash("Sadly, something is broken with our database. Whoops!")
        return redirect(url_for("index"))
    flash("Success registering!")
    session["token"] = "valid"
    return redirect(url_for("success"))
Ejemplo n.º 4
0
def show():
    db = MySQLConnection('mydb')
    query = "SELECT * FROM maillist"
    results = db.query_db(query)
    print(results)

    return render_template('users.html', results=results)
Ejemplo n.º 5
0
def results():
    db = MySQLConnection('mydb')
    query = "SELECT * FROM surveys ORDER BY id DESC LIMIT 1"
    results = db.query_db(query)
    print(results)

    return render_template('results.html', results=results)
Ejemplo n.º 6
0
def tweet():
    is_valid = validate_tweet(request.form)
    if is_valid:
        mysql = MySQLConnection('dojo_tweets')
        query = "INSERT INTO tweets (message, user_id) VALUES(%(message)s, %(userID)s);"
        data = {'message': request.form['tweet'], 'userID': session['userID']}
        new_tweet_id = mysql.query_db(query, data)
    return redirect('/dashboard')
Ejemplo n.º 7
0
def update_tweet(tweet_id):
    is_valid = validate_tweet(request.form)
    if is_valid:
        mysql = MySQLConnection('dojo_tweets')
        query = "UPDATE tweets SET message = %(message)s WHERE tweets.id = %(tweet_id)s"
        data = {'message': request.form['updated_msg'], 'tweet_id': tweet_id}
        mysql.query_db(query, data)
    return redirect('/dashboard')
Ejemplo n.º 8
0
def __get_password_hash(email: str) -> str:
    mysql = MySQLConnection("mydb")
    query = "SELECT password_hash " \
            "FROM peak_user " \
            "WHERE email = %(email)s"
    data = dict(email=email)
    r = mysql.query_db(query, data)

    if r:
        return r[0]["password_hash"]
Ejemplo n.º 9
0
def success():
    print("get /success")
    flash('You were successfully logged in')

    mysql = MySQLConnection("mydb")
    query = "SELECT email_address " \
            "FROM email_only;"
    emails = [r["email_address"] for r in mysql.query_db(query)]

    return render_template('success.html', emails=emails)
Ejemplo n.º 10
0
def edit_tweet(tweet_id):
    if session:
        mysql = MySQLConnection('dojo_tweets')
        query = "SELECT users.id FROM users LEFT JOIN tweets ON users.id = tweets.user_id WHERE tweets.id = %(tweet_id)s;"
        data = {'tweet_id': tweet_id}
        tweet_owner = mysql.query_db(query, data)
        user_mysql = MySQLConnection('dojo_tweets')
        user_query = "SELECT first_name, last_name, id FROM users WHERE users.id = %(userID)s;"
        user_data = {'userID': session['userID']}
        user = user_mysql.query_db(user_query, user_data)
        if session['userID'] == tweet_owner[0]['id']:
            mysql = MySQLConnection('dojo_tweets')
            query = "SELECT message FROM tweets WHERE tweets.id = %(tweet_id)s"
            data = {'tweet_id': tweet_id}
            message = mysql.query_db(query, data)
            return render_template('edit_tweet.html',
                                   tweet_id=tweet_id,
                                   current_user=user[0],
                                   message=message[0]['message'])
        else:
            flash("You can't edit tweet that isn't your own", 'errors')
            return render_template('edit_tweet.html',
                                   tweet_id=tweet_id,
                                   current_user=user[0],
                                   message="")
    return redirect('/registration')
Ejemplo n.º 11
0
def delete_message(ts):
    print("get /wall")
    mysql = MySQLConnection("mydb")
    query = "DELETE FROM board_message " \
            "WHERE ts = %(ts)s;"
    data = dict(ts=ts)
    mysql.query_db(query, data)

    flash(f"You deleted a message")

    return redirect(url_for("wall"))
Ejemplo n.º 12
0
def username():
    mysql = MySQLConnection("mydb")
    query = "SELECT username " \
            "FROM peak_user " \
            "WHERE username = %(username)s;"
    data = dict(username=request.form["username"])
    res = mysql.query_db(query, data)
    print(res)
    if len(res) > 0:
        return 'Username taken'
    else:
        return "Username available"
Ejemplo n.º 13
0
def send_message():
    print("post /wall")
    mysql = MySQLConnection("mydb")
    query = "INSERT INTO board_message(sender, recipient, content) " \
            "VALUE (%(sender)s, %(recipient)s, %(content)s);"
    data = dict(sender=session["email"],
                recipient=request.form["recipient"],
                content=request.form["content"])
    mysql.query_db(query, data)

    flash(f"You sent a message to {request.form['recipient']}")

    return redirect(url_for("wall"))
Ejemplo n.º 14
0
def login():
    mysql = MySQLConnection('dojo_tweets')
    query = "SELECT * FROM users WHERE users.email = %(email)s;"
    data = {'email': request.form['email']}
    user = mysql.query_db(query, data)
    print(user)
    if user:
        if bcrypt.check_password_hash(user[0]['password'],
                                      request.form['password']):
            session['userID'] = user[0]['id']
            return redirect('/dashboard')
    flash('You could not be logged in. Try again!', 'login error')
    return redirect('/registration')
Ejemplo n.º 15
0
def delete_message_ajax_post():
    print("post /wall/ajax_delete")
    print(request.form)
    # ts = request.form.keys()[0].replace('#delete_ajax', "")
    mysql = MySQLConnection("mydb")
    query = "DELETE FROM board_message " \
            "WHERE ts = %(ts)s;"
    data = dict(ts=request.form['ts'])
    mysql.query_db(query, data)

    flash(f"You deleted a message")

    return "success deleting"
Ejemplo n.º 16
0
def index_post():
    print("post /")

    email = request.form['email']

    if not __is_valid_email(email):  # test whether a field matches the pattern
        flash("Invalid email address!", "error")
        return redirect("/")

    mysql = MySQLConnection('mydb')
    query = "INSERT into email_only(email_address) VALUE(%(email)s);"
    data = dict(email=email)
    mysql.query_db(query, data)

    return redirect(url_for('success'))
Ejemplo n.º 17
0
def insert_module_usage(kaust_id, mode, hostname, name, path):
    with MySQLConnection() as cursor:
        sql = "INSERT INTO module_usage(kaust_id, full_name, when_date, mode, hostname, name, path) " \
              "VALUES(%s,%s,%s,%s,%s,%s,%s)"
        data = (kaust_id, get_full_name_from(kaust_id), datetime.now().date(),
                mode, hostname.lower(), name, path)
        cursor.execute(sql, data)
Ejemplo n.º 18
0
def login():
    flash('Hello')
    mysql = MySQLConnection("login")
    query = "SELECT * FROM users WHERE email = %(e)s;"
    data = {"e": request.form["email"]}
    result = mysql.query_db(query, data)
    if result:
        if bcrypt.check_password_hash(result[0]['hpwd'],
                                      request.form['password']):
            session['userid'] = result[0]['id']
            return render_template('welcome.html')
    flash("Please check password")
    test = bcrypt.generate_password_hash(request.form['password'])
    #if not EMAIL_REGEX.match(request.form['email']):
    #    flash("Invalid email address!")
    #    return render_template('registration.html')
    return render_template('registration.html')
Ejemplo n.º 19
0
def remove_admin(target_email):
    if 'email' in session:
        print("get /remove_admin")
        mysql = MySQLConnection("mydb")
        query = "SELECT admin_level " \
                "FROM peak_user " \
                "WHERE email = %(admin_email)s"
        data = dict(admin_email=session['email'])
        res = mysql.query_db(query, data)

    if not ('email' in session and res):
        flash("you're not signed in")
        return redirect(url_for("index"))

    if res[0]["admin_level"] != 9:
        flash("Sorry, you aren't an admin")
        return redirect(url_for("wall"))

    mysql = MySQLConnection("mydb")
    query = "UPDATE peak_user " \
        f"SET admin_level = 1 " \
        f"WHERE email = %(email)s;"
    data = dict(email=target_email)
    mysql.query_db(query, data)

    flash(f"lowered {target_email}'s admin level")

    return redirect(url_for("user"))
Ejemplo n.º 20
0
def suspend(target_email):
    if 'email' in session:
        print("get /admin")
        mysql = MySQLConnection("mydb")
        query = "SELECT admin_level " \
                "FROM peak_user " \
                "WHERE email = %(admin_email)s"
        data = dict(admin_email=session['email'])
        res = mysql.query_db(query, data)

    if not ('email' in session and res):
        flash("you're not signed in")
        return redirect(url_for("index"))

    if res[0]["admin_level"] != 9:
        flash("Sorry, you aren't an admin")
        return redirect(url_for("wall"))

    mysql = MySQLConnection("mydb")

    query = "UPDATE peak_user " \
        f"SET password_hash = '{b_crypt.generate_password_hash(str(secrets.token_hex(33)))}' " \
        f"WHERE email = %(email)s;"
    data = dict(email=target_email)
    mysql.query_db(query, data)

    flash("If the user exists, we've locked them out of their account by changing their password.")
    return redirect(url_for("user"))
Ejemplo n.º 21
0
def add_names():
    ids = []
    with MySQLConnection(autocommit=False) as select_cursor:
        select_cursor.execute("SELECT DISTINCT kaust_id FROM module_usage WHERE full_name = 'UNKNOWN'")
        row = select_cursor.fetchone()
        while row is not None:
            ids.append([str(c) for c in row])
            row = select_cursor.fetchone()

    with MySQLConnection() as insert_cursor:
        for kaust_id in ids:
            kaust_id = kaust_id[0]
            sql = """ UPDATE module_usage
                      SET full_name = %s
                      WHERE kaust_id = %s"""
            data = (get_full_name_from(kaust_id), kaust_id)
            print sql, data
            insert_cursor.execute(sql, data)
Ejemplo n.º 22
0
def make():
    print(request.form['email'])
    if not EMAIL_REGEX.match(request.form['email']):
        flash("Invalid email address.")
        return redirect('/')
    elif (len(request.form['email'])<1):
        flash("No email address typed in.")
        return redirect('/')
    else:
        query = "INSERT INTO maillist (email) VALUES (%(e)s);"
        data = {
            'e': request.form['email']
            }
        db = MySQLConnection('mydb')
        insert = db.query_db(query, data)
        print(query)
        flash("Successfully Added")
        return redirect("/list")
Ejemplo n.º 23
0
def wall():
    print("get /wall")
    print(session.get("token"))
    if session.get("token") != "valid":
        flash("You must be logged in to view this page")
        return redirect(url_for("index"))

    # Display link to user page for admins
    mysql = MySQLConnection("mydb")
    query = "SELECT admin_level " \
            "FROM peak_user " \
            "WHERE email = %(email)s"
    data = dict(email=session['email'])
    res = mysql.query_db(query, data)
    if res:
        admin_level = res[0]["admin_level"]
    else:
        admin_level = 1

    # Get other messages
    mysql = MySQLConnection("mydb")
    query = "SELECT sender, content, ts " \
            "FROM board_message " \
            "WHERE recipient = %(email)s" \
            "ORDER BY ts desc " \
            "LIMIT 20;"
    data = dict(email=session['email'])
    messages = mysql.query_db(query, data)
    if messages is False:
        flash("Sadly, there was an error with query 1")
        return redirect(url_for("index"))

    # Get other users
    mysql = MySQLConnection("mydb")
    query = "SELECT first_name, email " \
            "FROM peak_user " \
            "ORDER BY first_name;"
    users = mysql.query_db(query)
    if users is False:
        flash("Sadly, there was an error with query 2")
        return redirect(url_for("index"))
    # for message in messages:
    #     message["ts"] = str(message["ts"])

    return render_template("wall.html",
                           email=session["email"],
                           messages=messages,
                           users=users,
                           admin_level=admin_level)
Ejemplo n.º 24
0
def create():
    data = {
        "name": request.form['name'],
        "location": request.form['location'],
        "language": request.form['language'],
        "comments": request.form['comments']
    }
    if len(data['name']) < 1:
        flash("enter name")
        return redirect('/')
    elif len(data['comments']) > 120:
        flash("comment too long")
        return redirect('/')
    else:
        query = "INSERT INTO surveys (name, location, language, comment) VALUES (%(name)s, %(location)s, %(language)s, %(comments)s);"
        db = MySQLConnection('mydb')
        insert = db.query_db(query, data)
        flash("Successfully Added")
    return redirect("/results")
Ejemplo n.º 25
0
def username_search():
    print(request.form)
    print(request.form['username_search'])
    if request.form['username_search'] == str():
        return str()

    mysql = MySQLConnection("mydb")
    query = "SELECT username " \
            "FROM peak_user " \
            "WHERE username like %(query)s " \
            "ORDER BY username;"

    data = dict(query=request.form['username_search'] + '%%')
    res = mysql.query_db(query, data)
    html = str()
    for r in res:
        html += f'<li>{r["username"]}</li>'
    print(html)

    return html
Ejemplo n.º 26
0
def user():
    print("get /user")
    if 'email' not in session:
        flash("you're not signed in")
        return redirect(url_for('index'))

    mysql = MySQLConnection("mydb")
    query = "SELECT admin_level " \
            "FROM peak_user " \
            "WHERE email = %(email)s"
    data = dict(email=session['email'])
    res = mysql.query_db(query, data)
    if not res:
        flash("you're not signed in")
        return redirect(url_for("index"))
    if res[0]["admin_level"] != 9:
        flash("Sorry, you aren't an admin")
        return redirect(url_for("wall"))

    mysql = MySQLConnection("mydb")
    query = "SELECT first_name, last_name, email, admin_level " \
            "FROM peak_user " \
            "ORDER BY email;"
    users = mysql.query_db(query)

    return render_template("users.html", users=users)
Ejemplo n.º 27
0
def login():
    print(request.form)
    mySql = MySQLConnection('basic_regstration')
    query = 'SELECT * FROM users WHERE email = %(em)s'
    data = {'em': request.form['email']}
    pw = bcrypt.generate_password_hash(request.form['pw1'])
    pw_hash = mySql.query_db(query, data)
    print('*'*50)
    print('pw_hash', pw_hash[0]['password'])
    print('pw   ', pw)
    print('*'*50)
    session['fName'] = pw_hash[0]['first_name']
    session['lName'] = pw_hash[0]['last_name']
    session['email'] = pw_hash[0]['email']
    print(session)
    if bcrypt.check_password_hash(
            pw_hash[0]['password'], request.form['pw1']):
        session['login'] = True
        return redirect('/success')
    else:
        flash('Wrong Password')
        return redirect('/')
Ejemplo n.º 28
0
def signup():
    mysql = MySQLConnection('dojo_tweets')

    is_valid = validate_signup(request.form)
    if is_valid:
        pw_hash = bcrypt.generate_password_hash(request.form['password'])
        query = 'INSERT INTO users (first_name, last_name, birthdate, email, password) VALUES(%(fname)s, %(lname)s, %(bday)s, %(email)s, %(pw_hash)s);'
        data = {
            'fname': request.form['fname'],
            'lname': request.form['lname'],
            'bday': request.form['birthdate'],
            'email': request.form['email'],
            'pw_hash': pw_hash
        }
        new_user_id = mysql.query_db(query, data)
        session['userID'] = new_user_id
        # return redirect('/dashboard')
        if new_user_id:
            flash('Registered successfully. Please log in.', 'success')
        else:
            flash('Unsuccessful. Please try again', 'errors')
    return redirect('/registration')
Ejemplo n.º 29
0
def users():
    if session:
        user_mysql = MySQLConnection('dojo_tweets')
        user_query = "SELECT first_name, last_name, id FROM users WHERE users.id = %(userID)s;"
        user_data = {'userID': session['userID']}
        user = user_mysql.query_db(user_query, user_data)
        users_mysql = MySQLConnection('dojo_tweets')
        users_query = f"SELECT * FROM users WHERE users.id != {session['userID']}"
        all_users = users_mysql.query_db(users_query)
        following_users_mysql = MySQLConnection('dojo_tweets')
        following_users_query = f"SELECT GROUP_CONCAT(follows.following_id) as following_id FROM users LEFT JOIN follows ON users.id = follows.user_id WHERE users.id = {session['userID']} GROUP BY users.id;"
        following_users = following_users_mysql.query_db(following_users_query)
        if following_users[0]['following_id']:
            following_id = following_users[0]['following_id'].split(',')
        else:
            following_id = []
        return render_template('users.html',
                               current_user=user[0],
                               all_users=all_users,
                               following_id=following_id)
    return redirect('/registration')
Ejemplo n.º 30
0
def dashboard():
    if session:
        user_mysql = MySQLConnection('dojo_tweets')
        user_query = "SELECT first_name, last_name, id FROM users WHERE users.id = %(userID)s;"
        user_data = {'userID': session['userID']}
        user = user_mysql.query_db(user_query, user_data)
        tweets_mysql = MySQLConnection('dojo_tweets')
        tweets_query = "SELECT tweets.id as tweet_id, tweets.message, users.id as user_id, users.first_name, users.last_name, tweets.created_at, tweets.updated_at, COUNT(likes.id) as num_of_likes, GROUP_CONCAT(likes.user_id) as liked_by FROM tweets LEFT JOIN users ON tweets.user_id = users.id LEFT JOIN likes ON likes.tweet_id = tweets.id GROUP BY message ORDER BY tweets.created_at DESC;"
        tweets = tweets_mysql.query_db(tweets_query)
        following_users_mysql = MySQLConnection('dojo_tweets')
        following_users_query = f"SELECT GROUP_CONCAT(follows.following_id) as following_id FROM users LEFT JOIN follows ON users.id = follows.user_id WHERE users.id = {session['userID']} GROUP BY users.id;"
        following_users = following_users_mysql.query_db(following_users_query)
        if following_users[0]['following_id']:
            following_id = following_users[0]['following_id'].split(',')
        else:
            following_id = []
        for tweet in tweets:
            if tweet['liked_by']:
                tweet['liked_by'] = tweet['liked_by'].split(',')
        return render_template('dashboard.html',
                               current_user=user[0],
                               tweets=tweets,
                               following_id=following_id)
    return redirect('/registration')