activate.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import arrow
  2. from flask import request, redirect, url_for, flash, render_template
  3. from flask_login import login_user, current_user
  4. from app.auth.base import auth_bp
  5. from app.extensions import db
  6. from app.log import LOG
  7. from app.models import ActivationCode
  8. @auth_bp.route("/activate", methods=["GET", "POST"])
  9. def activate():
  10. if current_user.is_authenticated:
  11. return (
  12. render_template("auth/activate.html", error="You are already logged in"),
  13. 400,
  14. )
  15. code = request.args.get("code")
  16. activation_code: ActivationCode = ActivationCode.get_by(code=code)
  17. if not activation_code:
  18. return (
  19. render_template("auth/activate.html", error="Activation code not found"),
  20. 400,
  21. )
  22. if activation_code.expired and activation_code.expired < arrow.now():
  23. return (
  24. render_template(
  25. "auth/activate.html",
  26. error="Activation code is expired",
  27. show_resend_activation=True,
  28. ),
  29. 400,
  30. )
  31. user = activation_code.user
  32. user.activated = True
  33. login_user(user)
  34. # activation code is to be used only once
  35. activation_code.delete()
  36. db.session.commit()
  37. flash("Your account has been activated", "success")
  38. # The activation link contains the original page, for ex authorize page
  39. if "next" in request.args:
  40. next_url = request.args.get("next")
  41. LOG.debug("redirect user to %s", next_url)
  42. return redirect(next_url)
  43. else:
  44. LOG.debug("redirect user to dashboard")
  45. return redirect(url_for("dashboard.index"))