46 lines
1.8 KiB
Python
46 lines
1.8 KiB
Python
from urllib.parse import urlparse
|
|
from flask import Blueprint, render_template, redirect, url_for, flash, request
|
|
from flask_login import login_user, logout_user, login_required, current_user
|
|
from app import db
|
|
from app.models import User
|
|
from app.auth.forms import RegistrationForm, LoginForm
|
|
|
|
auth_bp = Blueprint("auth", __name__)
|
|
|
|
@auth_bp.route("/register", methods=["GET", "POST"])
|
|
def register():
|
|
if current_user.is_authenticated:
|
|
return redirect(url_for("main.index"))
|
|
form = RegistrationForm()
|
|
if form.validate_on_submit():
|
|
user = User(username=form.username.data, email=form.email.data)
|
|
user.set_password(form.password.data)
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
flash("Account created. You can log in now.", "success")
|
|
return redirect(url_for("auth.login"))
|
|
return render_template("auth/register.html", form=form)
|
|
|
|
@auth_bp.route("/login", methods=["GET", "POST"])
|
|
def login():
|
|
if current_user.is_authenticated:
|
|
return redirect(url_for("main.index"))
|
|
form = LoginForm()
|
|
if form.validate_on_submit():
|
|
user = User.query.filter_by(email=form.email.data).first()
|
|
if user is None or not user.check_password(form.password.data):
|
|
flash("Invalid email or password.", "danger")
|
|
return redirect(url_for("auth.login"))
|
|
login_user(user, remember=form.remember_me.data)
|
|
next_page = request.args.get("next")
|
|
if not next_page or urlparse(next_page).netloc != "":
|
|
next_page = url_for("main.index")
|
|
return redirect(next_page)
|
|
return render_template("auth/login.html", form=form)
|
|
|
|
@auth_bp.route("/logout")
|
|
@login_required
|
|
def logout():
|
|
logout_user()
|
|
flash("You have been logged out.", "info")
|
|
return redirect(url_for("main.index"))
|