app.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """
  2. Authentication module
  3. """
  4. import os
  5. from flask_login import login_required, login_user, logout_user, current_user
  6. from flask_menu import Menu, register_menu
  7. from flask import render_template, request, redirect, url_for, flash, Blueprint, abort, jsonify
  8. from jinja2 import TemplateNotFound
  9. from app import app, login_manager, db
  10. from app.models import User, Page
  11. BLUEPRINT = Blueprint(
  12. 'auth',
  13. __name__,
  14. template_folder='templates'
  15. )
  16. @BLUEPRINT.route("/login", methods=["GET", "POST"])
  17. def login():
  18. """Handle login page and data"""
  19. if request.method == 'POST':
  20. email = request.form['email']
  21. password = request.form['password']
  22. user = User.query.filter(User.email == email).first()
  23. if user:
  24. if not user.approved:
  25. flash('Account not approved yet.', 'warning')
  26. if user.check_password(password):
  27. login_user(user, remember=True)
  28. flash('Successfully loggend in.', 'success')
  29. if request.args.get("next"):
  30. return redirect(request.args.get('next'))
  31. return redirect(url_for('backend.index'))
  32. flash('Password Incorrect.', 'warning')
  33. return render_template('login.j2', login_email=email)
  34. flash('Email not found.', 'warning')
  35. return render_template('login.j2')
  36. @BLUEPRINT.route("/register", methods=["POST"])
  37. def register():
  38. """Register a new user"""
  39. name = request.form['name'] if 'name' in request.form else None
  40. email = request.form['email'] if 'email' in request.form else None
  41. password = request.form['password'] if 'email' in request.form else None
  42. if name is None:
  43. flash('Fill in the name.', 'warning')
  44. return render_template('login.j2')
  45. if email is None:
  46. flash('Fill in the email.', 'warning')
  47. return render_template(
  48. 'login.j2',
  49. name=name
  50. )
  51. if password is None:
  52. flash('Fill in the password.', 'warning')
  53. return render_template(
  54. 'login.j2',
  55. name=name,
  56. email=email
  57. )
  58. user = User.query.filter(User.email == email).first()
  59. if user is not None:
  60. flash('Email already taken.', 'warning')
  61. return render_template(
  62. 'login.j2',
  63. name=name,
  64. )
  65. user = User()
  66. user.name = name
  67. user.email = email
  68. user.password = password
  69. db.session.add(user)
  70. db.session.commit()
  71. flash('Successfully registered account "%s". Wait for verfication.' % (user.name), 'success')
  72. return render_template('login.j2')
  73. @BLUEPRINT.route("/logout")
  74. @login_required
  75. def logout():
  76. """Logout function for users"""
  77. logout_user()
  78. return redirect('')