Guest User

Untitled

a guest
Aug 6th, 2018
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.41 KB | None | 0 0
  1. from LoginDemoApp import app, db, bcrypt, serializer, mail
  2. from LoginDemoApp.database_tables import User
  3. from LoginDemoApp.forms import RegistrationForm, LoginForm
  4. from flask import render_template, url_for, flash, Markup, redirect, request
  5. from flask_login import login_user, current_user, logout_user, login_required
  6. from flask_mail import Message
  7. from itsdangerous import SignatureExpired, BadTimeSignature
  8.  
  9.  
  10. @app.route("/")
  11. @app.route("/home")
  12. def home():
  13. return render_template('home.html')
  14.  
  15.  
  16. @app.route("/signUp", methods=['GET', 'POST'])
  17. def sign_up():
  18. form = RegistrationForm()
  19. if form.validate_on_submit():
  20. # Extract user inputs
  21. username = form.username.data.lower()
  22. email = form.email.data.lower()
  23. password = form.password.data
  24.  
  25. # Hash password
  26. password = bcrypt.generate_password_hash(password)
  27.  
  28. # Store user inputs in database
  29. user = User(username=username, email=email, password=password, email_confirmed=False)
  30. db.session.add(user)
  31. db.session.commit()
  32.  
  33. # Redirect to send_email route to send confirmation mail
  34. return redirect(url_for('send_email', token=serializer.dumps(email, salt='email')))
  35. return render_template('sign_up.html', form=form)
  36.  
  37.  
  38. @app.route("/login", methods=['GET', 'POST'])
  39. def login():
  40. # If user is already logged in redirect to home page
  41. if current_user.is_authenticated:
  42. return redirect(url_for('home'))
  43.  
  44. # Create LoginForm() object to validate user input when its submitted as a POST request
  45. form = LoginForm()
  46.  
  47. # If user input has been submitted and been validated log the user in
  48. if form.validate_on_submit():
  49. # Extract user inputs
  50. email = form.email.data.lower()
  51. password = form.password.data
  52.  
  53. # Search for user in database
  54. user = User.query.filter_by(email=email).first()
  55.  
  56. # If user has been found, the password matches and users email has been confirmed, log user in
  57. if user and bcrypt.check_password_hash(user.password, password) and user.email_confirmed:
  58. login_user(user, remember=form.remember.data)
  59.  
  60. # If login is being accessed from a redirect store target page in variable called next_page
  61. next_page = request.args.get('next')
  62.  
  63. # Redirect to target page or home page based on how user got to the login page
  64. return redirect(next_page) if next_page else redirect(url_for('home'))
  65.  
  66. # If email has not been confirmed yet offer user to resend confirmation mail
  67. elif user and bcrypt.check_password_hash(user.password, password) and not user.email_confirmed:
  68. flash(Markup('Please confirm your email address first <a href="%s">(Resend Email)</a>' % url_for('send_email', token=serializer.dumps(email, salt='email'))))
  69.  
  70. # Otherwise the user must have entered wrong credentials
  71. else:
  72. flash('Login failed. Please check your credentials')
  73.  
  74. # If user is not already logged in redirect to login page
  75. return render_template('login.html', form=form)
  76.  
  77.  
  78. # This route can only be accessed if user is already logged in
  79. @login_required
  80. @app.route("/logout")
  81. def logout():
  82. # Log out user and redirect to home page
  83. logout_user()
  84. return redirect(url_for('home'))
  85.  
  86.  
  87. # This route can only be accessed with a valid token
  88. # When accessed it confirms the email the token is associated with
  89. @app.route('/confirm_email/<token>')
  90. def confirm_email(token):
  91. try:
  92. # Extract email address from token
  93. email = serializer.loads(token, salt='email', max_age=1800)
  94.  
  95. # Update confirmed email flag to true
  96. user = User.query.filter_by(email=email).first()
  97. user.email_confirmed = True
  98. db.session.add(user)
  99. db.session.commit()
  100.  
  101. # Notify user with success message
  102. flash('Your account has been created! You are now able to log in')
  103.  
  104. # If token is expired or invalid notify user
  105. except (SignatureExpired, BadTimeSignature):
  106. if SignatureExpired:
  107. return 'Token expired'
  108. elif BadTimeSignature:
  109. return 'Invalid token'
  110.  
  111. # If email confirmation was successful return to login page so user can login
  112. return redirect(url_for('login'))
  113.  
  114.  
  115. # This route is accessed whenever a confirmation mail need to be send
  116. # Instead of an email a token of the mail is being passed to the URL, to make brute force attacks more difficult
  117. @app.route('/send_mail/<token>')
  118. def send_email(token):
  119.  
  120. # Extract email address from token
  121. email = serializer.loads(token, salt='email', max_age=1800)
  122.  
  123. # Send confirmation mail to extracted email address
  124. token = serializer.dumps(email, salt='email')
  125.  
  126. # Email head message
  127. msg = Message('FlaskLoginDemo.PythonAnywhere.com -- Confirm your email', sender='your@mail.com', recipients=[email])
  128.  
  129. # Email body message
  130. msg.body = '''Please click this link to confirm your email: %s
  131. If you did not make this request simply ignore this email.''' \
  132. % url_for('confirm_email', token=token, _external=True)
  133.  
  134. # Send email
  135. mail.send(msg)
  136.  
  137. # Notify user that email has been send
  138. flash_msg = 'A confirmation email has been send to %s. Please follow its instructions to login. <a href="%s">' \
  139. '(Resend Email)</a>' % (email, url_for('send_email', token=serializer.dumps(email, salt='email')))
  140.  
  141. flash(Markup(flash_msg))
  142.  
  143. # Redirect to login page
  144. return redirect(url_for('login'))
Add Comment
Please, Sign In to add comment