Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #imports
- from flask import Flask, request, redirect, render_template, session, flash
- # import MySQL from local file
- from mysqlconnection import MySQLConnector
- # import Regular Expressions for form checks
- import re
- # imports the Bcrypt module
- from flask.ext.bcrypt import Bcrypt
- app = Flask(__name__)
- bcrypt = Bcrypt(app)
- #set session key
- app.secret_key = "MySecretKey" #necessary for session
- # Define Database
- mysql = MySQLConnector(app, 'login_registration')
- # global vars
- numbers = re.compile('[0-9]')
- uppercase = re.compile('[A-Z]')
- email_validator = re.compile('[a-zA-Z0-9\._-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9]+')
- # home page working
- # this will load a page that has 2 forms one for registration and login
- @app.route('/', methods=['GET'])
- def index():
- return render_template('index.html')
- # we are going to add functions to create new users and login users
- # registration working
- @app.route('/create_user', methods=['POST'])
- def create_user():
- email = request.form['email']
- first_name = request.form['first_name']
- last_name = request.form['last_name']
- password = request.form['password']
- # run validations and if they are successful we can create the password hash with bcrypt
- session['flash'] = 0
- validate_name(request.form)
- validate_email(request.form)
- validate_password(request.form)
- #validate_birthdate(request.form)
- if (session['flash'] != 0):
- print "ERRORS FOUND"
- return redirect('/')
- else: # add user to database and redirect to home.html
- pw_hash = bcrypt.generate_password_hash(password)
- #pw_hash = password
- # now we insert the new user into the database
- insert_query = "INSERT INTO users (email, first_name, last_name, password, created_at, updated_at) VALUES (:email, :first_name, :last_name, :pw_hash, NOW(), NOW())"
- print pw_hash
- query_data = { 'email': email, 'first_name': first_name, 'last_name': last_name, 'pw_hash': pw_hash }
- mysql.query_db(insert_query, query_data)
- # redirect to success page
- return render_template('home.html', data=query_data)
- #Login Broken
- #Now to use this when trying to login we might do it like so:
- @app.route('/login', methods=['POST'])
- def login():
- #validate the forms are populated and correct
- # validate_email(request.form)
- # validate_password(request.form)
- # set vars
- email = request.form['email']
- password = request.form['password']
- # pw_hash = bcrypt.generate_password_hash(password)
- user_query = "SELECT * FROM users WHERE email = :email LIMIT 1"
- query_data = { 'email': email }
- user = mysql.query_db(user_query, query_data) # user will be returned in a list
- # is password valid?
- if bcrypt.check_password_hash(user[0]['password'], password):
- # login user
- print "Success!"*5
- return render_template('home.html', data=user)
- else:
- flash("User/Password incorrect - please try again")
- print "Failed!"*5, password, user[0]['password']
- return redirect('/')
- # set flash error message and redirect to login page
- # validation definitions
- def validate_name(form):
- first = form['first_name']
- last = form['last_name']
- if len(first) == 0:
- flash("First Name can't be left empty")
- session['flash'] += 1
- else:
- if (numbers.search(first) != None):
- flash("Name field can't have numbers")
- if len(last) == 0:
- flash("Last Name can't be left empty")
- session['flash'] += 1
- else:
- if (numbers.search(last) != None):
- flash("Name field can't have numbers")
- return
- def validate_email(form):
- email = form['email']
- if len(email) == 0:
- flash("Email Address can't be left empty")
- session['flash'] += 1
- else:
- if email_validator.match(email) == None:
- flash("Invalid Email Address!")
- session['flash'] += 1
- return
- def validate_password(form):
- passwd = form['password']
- passconf = form['confirm_password']
- if len(passwd) == 0:
- flash("Password Must Be Filled Out")
- session['flash'] += 1
- elif len(passwd) < 3:
- flash("Password must contain at least 3 characters")
- session['flash'] += 1
- elif (numbers.search(passwd) == None):
- flash("Password must contain at least 1 number")
- session['flash'] += 1
- elif (uppercase.search(passwd) == None):
- flash("Password must contain at least 1 Uppercase Character")
- session['flash'] += 1
- if (passwd != passconf):
- flash("Passwords Don't Match")
- session['flash'] += 1
- return
- def validate_birthdate(form):
- year = form['year']
- month = form['month']
- day = form['day']
- birthdate = ''
- try:
- birthdate = date(int(year), int(month), int(day))
- session['birthdate'] = birthdate
- except Exception, err:
- flash("Invalid date - '{}'".format(err), 'dob')
- session['flash'] += 1
- if (birthdate):
- today = date.today()
- diff = today - birthdate
- if (diff.days <= 0):
- flash("Birthday must be in the past.")
- session['flash'] += 1
- return
- if __name__ == "__main__":
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement