Esempio n. 1
0
def create():
    print("Got post info")
    print(request.form)
    # include some logic to validate user input before adding them to the database!
    # Going to use this data twice, so putting it into a variable
    first_name = request.form["first_name"]
    last_name = request.form["last_name"]
    form_email = request.form["email"]
    pass_word = request.form["password"]
    print(form_email, "LOOK HERE")
    #Setting up a query to retrieve all the email addresses so we can verify the new one doesn't already exist in the DB
    mysql = connectToMySQL("login_and_reg")
    query = "SELECT email FROM users;"
    results = mysql.query_db(query)
    print(results)
    is_valid = True
    if len(first_name) < 2 or not first_name.isalpha():
        is_valid = False
        flash(
            u"First name must contain at least two letters and only contain letters.",
            'register')
    if len(last_name) < 2 or not last_name.isalpha():
        is_valid = False
        flash(
            u"Last name must contain at least two letters and only contain letters.",
            'register')
    if not EMAIL_REGEX.match(form_email):
        is_valid = False
        flash(u"Invalid email address!", 'register')
    if not pass_word == request.form["confirm_password"]:
        is_valid = False
        flash(u"Password was not confirmed!", 'register')
    for result in results:
        if form_email == result["email"]:
            print("------------------------")
            is_valid = False
            flash(u"Email address already exists!", "register")

    # create the hash
    pw_hash = bcrypt.generate_password_hash(pass_word)
    print(pw_hash)
    # prints something like b'$2b$12$sqjyok5RQccl9S6eFLhEPuaRaJCcH3Esl2RWLm/cimMIEnhnLb7iC'
    # be sure you set up your database so it can store password hashes this long (60 characters)copy
    if is_valid:
        mysql = connectToMySQL("login_and_reg")
        query = "INSERT INTO users (first_name, last_name, email, password_hash) VALUES (%(fname)s, %(lname)s, %(email)s, %(password_hash)s);"
        # put the pw_hash in our data dictionary, NOT the password the user provided
        data = {
            "fname": first_name,
            "lname": last_name,
            "email": form_email,
            "password_hash": pw_hash
        }
        mysql.query_db(query, data)
        session["first_name"] = first_name
        print(session["first_name"], "---------------------")
        # never render on a post, always redirect!
        print(is_valid)
        return redirect("/success")
    return redirect('/')
Esempio n. 2
0
def login_reg():
	validations = 0
	if request.form.get('login') is not None:
		if len(request.form['email'])<1 or not EMAIL_REGEX.match(request.form['email']):
			validations +=1
			flash('Email cannot be blank or is invalid')
		if len(request.form['password'])<1:
			validations +=1
			flash('Password was empty')
		if validations == 0 :
			db = connectToMySQL('jam_space')
			query = 'SELECT password, username, id FROM users WHERE email = "{}"'.format(request.form['email'])
			user = db.query_db(query)
			if user and bcrypt.check_password_hash(user[0]['password'], request.form['password']):
				session['username'] = user[0]['username']
				session['id'] = user[0]['id']
				return redirect('/dashboard')
			else:
				flash('There is no account associated with this email')
		return redirect('/')

	elif request.form.get('register') is not None:
		if len(request.form['username'])<3:
			validations += 1
			flash('Username needs to be longer than 3 characters')
		if len(request.form['email'])<1 or not EMAIL_REGEX.match(request.form['email']):
			validations +=1
			flash('Email cannot be blank or is invalid')
		db = connectToMySQL('jam_space')
		query = 'SELECT username FROM users WHERE email = "{}"'.format(request.form['email'])
		user = db.query_db(query)
	
		if len(user) > 0:
			validations +=1
			flash('Email already in use!')
		if len(request.form['password'])<4 or request.form['password'] != request.form['c_password']:
			validations +=1
			flash('Password cannot be blank or does not match')
		if validations == 0 :
			password = bcrypt.generate_password_hash(request.form['password'])
			db = connectToMySQL('jam_space')
			query = 'INSERT INTO users (username, email, password, created_at, updated_at) VALUES (%(username)s, %(email)s, %(password)s, NOW(), NOW())'
			data = {
				'username': request.form['username'],
				'email': request.form['email'],
				'password': password
			}
			db.query_db(query, data)
			db = connectToMySQL('jam_space')
			query = "SELECT id, username FROM users WHERE email ='{}'".format(request.form['email'])
			user = db.query_db(query)
			session['username'] = user[0]['username']
			session['id'] = user[0]['id']
			return redirect('/dashboard')
		elif validations >= 1:
			return redirect('/')
Esempio n. 3
0
def dashboard():
	db = connectToMySQL('jam_space')
	if session.get('username') is None:
		return redirect('/')
	query = "SELECT posts.id, posts.content, posts.created_at, users.username FROM posts LEFT JOIN users ON posts.user_id=users.id"
	posts = db.query_db(query)
	db = connectToMySQL('jam_space')
	query = "SELECT comments.id, comments.content, comments.created_at, comments.user_id, users.username, posts.id AS post_id FROM comments LEFT JOIN users ON comments.user_id=users.id LEFT JOIN posts ON comments.post_id=posts.id"
	comments = db.query_db(query)

	return render_template('index.html', posts=posts, comments=comments)
def index():
    mysql = connectToMySQL(
        'first_flask')  # call the function, passing in the name of our db
    friends = mysql.query_db(
        'SELECT * FROM friends;'
    )  # call the query_db function, pass in the query as a string
    print(friends)
    return render_template("index.html")
Esempio n. 5
0
def post():
	db = connectToMySQL('jam_space')
	if request.form.get('post') is not None:
		query = 'INSERT INTO posts (content, user_id, created_at, updated_at) VALUES (%(content)s, %(user_id)s, NOW(), NOW())'
		data = {
			'content': request.form['content'],
			'user_id': session['id']
		}
		db.query_db(query, data)
		return redirect('/dashboard')
	elif request.form.get('comment') is not None:
		db = connectToMySQL('jam_space')
		query = "INSERT INTO comments (content, user_id, post_id, created_at, updated_at) VALUES (%(content)s, %(user_id)s, %(post_id)s, NOW(), NOW())"
		data = {
			'content': request.form['content'],
			'user_id': session['id'],
			'post_id': request.form['post_id']
		}
		db.query_db(query, data)
		return redirect('/dashboard')
Esempio n. 6
0
def deletePost():

	db = connectToMySQL('jam_space')
	if request.form.get('id') is not None:
		query = ('DELETE FROM posts WHERE id = %(id)s and user_id = %(userid)s')
		data = {
			"id": request.form.get('id'),
			"userid" : session['id']
		}
		db.query_db(query, data)
		return redirect('/dashboard')
	else: 
		return redirect('/dashboard')
Esempio n. 7
0
def login():
    # see if the username provided exists in the database
    mysql = connectToMySQL("login_and_reg")
    query = "SELECT * FROM users WHERE email = %(email)s;"
    data = {"email": request.form["email"]}
    result = mysql.query_db(query, data)
    print(result, "!!!!!!!!!!!!!!!!!!!!!!!!!")
    if len(result) > 0:
        # use bcrypt's check_password_hash method, passing the hash from our database and the password from the form
        if bcrypt.check_password_hash(result[0]['password_hash'],
                                      request.form['password_hash']):
            # if we get True after checking the password, we may put the user id in session
            session['first_name'] = result[0]['first_name']
            print(session['first_name'], "?????????????????????????????")
            # never render on a post, always redirect!
            return redirect('/success')
    # if we didn't find anything in the database by searching by username or if the passwords don't match,
    # flash an error message and redirect back to a safe route
    flash(u"You could not be logged in.", 'login')
    return redirect("/")