您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from flask import Blueprint, render_template, redirect, url_for, request, flash
  2. from werkzeug.security import generate_password_hash, check_password_hash
  3. from flask_login import login_user, logout_user, login_required
  4. from .models import User
  5. from . import db
  6. auth = Blueprint('auth', __name__)
  7. @auth.route('/login')
  8. def login():
  9. return render_template('login.html')
  10. @auth.route('/login', methods=['POST'])
  11. def login_post():
  12. email = request.form.get('email')
  13. password = request.form.get('password')
  14. remember = True if request.form.get('remember') else False
  15. user = User.query.filter_by(email=email).first()
  16. # check if the user actually exists
  17. # take the user-supplied password, hash it, and compare it to the hashed password in the database
  18. if not user or not check_password_hash(user.password, password):
  19. flash('Please check your login details and try again.')
  20. return redirect(url_for('auth.login')) # if the user doesn't exist or password is wrong, reload the page
  21. # if the above check passes, then we know the user has the right credentials
  22. login_user(user, remember=remember)
  23. return redirect(url_for('main.profile'))
  24. @auth.route('/signup')
  25. def signup():
  26. return render_template('signup.html')
  27. @auth.route('/signup', methods=['POST'])
  28. def signup_post():
  29. email = request.form.get('email')
  30. name = request.form.get('name')
  31. password = request.form.get('password')
  32. user = User.query.filter_by(email=email).first() # if this returns a user, then the email already exists in database
  33. if user: # if a user is found, we want to redirect back to signup page so user can try again
  34. flash('Email address already exists')
  35. return redirect(url_for('auth.signup'))
  36. # create a new user with the form data. Hash the password so the plaintext version isn't saved.
  37. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'))
  38. # add the new user to the database
  39. db.session.add(new_user)
  40. db.session.commit()
  41. return redirect(url_for('auth.login'))
  42. @auth.route('/logout')
  43. @login_required
  44. def logout():
  45. logout_user()
  46. return redirect(url_for('main.index'))