Advertisement
Guest User

Untitled

a guest
Jun 5th, 2016
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.67 KB | None | 0 0
  1. #imports
  2. from flask import Flask, request, redirect, render_template, session, flash
  3. # import MySQL from local file
  4. from mysqlconnection import MySQLConnector
  5. # import Regular Expressions for form checks
  6. import re
  7. # imports the Bcrypt module
  8. from flask.ext.bcrypt import Bcrypt
  9. app = Flask(__name__)
  10. bcrypt = Bcrypt(app)
  11.  
  12. #set session key
  13. app.secret_key = "MySecretKey" #necessary for session
  14. # Define Database
  15. mysql = MySQLConnector(app, 'login_registration')
  16.  
  17. # global vars
  18. numbers = re.compile('[0-9]')
  19. uppercase = re.compile('[A-Z]')
  20. email_validator = re.compile('[a-zA-Z0-9\._-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9]+')
  21.  
  22. # home page working
  23. # this will load a page that has 2 forms one for registration and login
  24. @app.route('/', methods=['GET'])
  25. def index():
  26. return render_template('index.html')
  27. # we are going to add functions to create new users and login users
  28.  
  29. # registration working
  30. @app.route('/create_user', methods=['POST'])
  31. def create_user():
  32. email = request.form['email']
  33. first_name = request.form['first_name']
  34. last_name = request.form['last_name']
  35. password = request.form['password']
  36.  
  37. # run validations and if they are successful we can create the password hash with bcrypt
  38. session['flash'] = 0
  39. validate_name(request.form)
  40. validate_email(request.form)
  41. validate_password(request.form)
  42. #validate_birthdate(request.form)
  43.  
  44. if (session['flash'] != 0):
  45. print "ERRORS FOUND"
  46. return redirect('/')
  47. else: # add user to database and redirect to home.html
  48. pw_hash = bcrypt.generate_password_hash(password)
  49. #pw_hash = password
  50. # now we insert the new user into the database
  51. 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())"
  52. print pw_hash
  53. query_data = { 'email': email, 'first_name': first_name, 'last_name': last_name, 'pw_hash': pw_hash }
  54. mysql.query_db(insert_query, query_data)
  55. # redirect to success page
  56. return render_template('home.html', data=query_data)
  57.  
  58. #Login Broken
  59. #Now to use this when trying to login we might do it like so:
  60. @app.route('/login', methods=['POST'])
  61. def login():
  62. #validate the forms are populated and correct
  63. # validate_email(request.form)
  64. # validate_password(request.form)
  65. # set vars
  66. email = request.form['email']
  67. password = request.form['password']
  68. # pw_hash = bcrypt.generate_password_hash(password)
  69. user_query = "SELECT * FROM users WHERE email = :email LIMIT 1"
  70. query_data = { 'email': email }
  71. user = mysql.query_db(user_query, query_data) # user will be returned in a list
  72. # is password valid?
  73. if bcrypt.check_password_hash(user[0]['password'], password):
  74. # login user
  75. print "Success!"*5
  76. return render_template('home.html', data=user)
  77. else:
  78. flash("User/Password incorrect - please try again")
  79. print "Failed!"*5, password, user[0]['password']
  80. return redirect('/')
  81. # set flash error message and redirect to login page
  82.  
  83. # validation definitions
  84. def validate_name(form):
  85. first = form['first_name']
  86. last = form['last_name']
  87.  
  88. if len(first) == 0:
  89. flash("First Name can't be left empty")
  90. session['flash'] += 1
  91. else:
  92. if (numbers.search(first) != None):
  93. flash("Name field can't have numbers")
  94. if len(last) == 0:
  95. flash("Last Name can't be left empty")
  96. session['flash'] += 1
  97. else:
  98. if (numbers.search(last) != None):
  99. flash("Name field can't have numbers")
  100. return
  101.  
  102. def validate_email(form):
  103. email = form['email']
  104. if len(email) == 0:
  105. flash("Email Address can't be left empty")
  106. session['flash'] += 1
  107. else:
  108. if email_validator.match(email) == None:
  109. flash("Invalid Email Address!")
  110. session['flash'] += 1
  111. return
  112.  
  113. def validate_password(form):
  114. passwd = form['password']
  115. passconf = form['confirm_password']
  116.  
  117. if len(passwd) == 0:
  118. flash("Password Must Be Filled Out")
  119. session['flash'] += 1
  120. elif len(passwd) < 3:
  121. flash("Password must contain at least 3 characters")
  122. session['flash'] += 1
  123. elif (numbers.search(passwd) == None):
  124. flash("Password must contain at least 1 number")
  125. session['flash'] += 1
  126. elif (uppercase.search(passwd) == None):
  127. flash("Password must contain at least 1 Uppercase Character")
  128. session['flash'] += 1
  129.  
  130. if (passwd != passconf):
  131. flash("Passwords Don't Match")
  132. session['flash'] += 1
  133. return
  134.  
  135. def validate_birthdate(form):
  136. year = form['year']
  137. month = form['month']
  138. day = form['day']
  139. birthdate = ''
  140.  
  141. try:
  142. birthdate = date(int(year), int(month), int(day))
  143. session['birthdate'] = birthdate
  144. except Exception, err:
  145. flash("Invalid date - '{}'".format(err), 'dob')
  146. session['flash'] += 1
  147.  
  148. if (birthdate):
  149. today = date.today()
  150. diff = today - birthdate
  151. if (diff.days <= 0):
  152. flash("Birthday must be in the past.")
  153. session['flash'] += 1
  154. return
  155.  
  156. if __name__ == "__main__":
  157. app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement