from flask import render_template,redirect, request, url_for, flash
from . import auth
from flask_login import login_user, logout_user
from ..models import User
from .forms import LoginForm, RegistrationForm

from .. import db

# 登录路由
@auth.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        print("xxxxx",User.query.all())
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            # login_user(user, form.remember.data)
            return redirect(url_for("main.index"))
            #return redirect(request.args.get("next") or url_for("main.index"))
        flash("Invalid username or password")

    return render_template("auth/login.html", form=form)

# 退出登入
@auth.route("/logout", methods=["GET", "POST"])
def logout():
    logout_user()
    flash("You have been logged out.")
    return redirect(url_for("main.index"))


# 注册路由
@auth.route("/register", methods=["GET", "POST"])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username = form.username.data,
                    password=form.password.data,
                    )
        db.session.add(user)
        db.session.commit()
        flash("You can now login.")
        return redirect(url_for("auth.login"))
    return render_template("auth/register.html", form=form)
















