mirror of
https://github.com/minetest/contentdb.git
synced 2025-01-10 06:57:34 +01:00
Remove flask_user and use flask_login directly, with partial feature support
This commit is contained in:
parent
2358ed1b24
commit
5ef15e91d4
app
__init__.pydefault_data.pymodels.pytemplate_filters.py
config.example.cfgrequirements.lock.txtrequirements.txtblueprints
admin
api
github
metapackages
notifications
packages
tasks
threads
todo
users
templates
usermgr.pyutils.py@ -16,7 +16,6 @@
|
||||
|
||||
|
||||
from flask import *
|
||||
from flask_user import *
|
||||
from flask_gravatar import Gravatar
|
||||
import flask_menu as menu
|
||||
from flask_mail import Mail
|
||||
@ -24,6 +23,7 @@ from flask_github import GitHub
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
from flask_flatpages import FlatPages
|
||||
from flask_babel import Babel
|
||||
from flask_login import logout_user, current_user
|
||||
import os, redis
|
||||
|
||||
app = Flask(__name__, static_folder="public/static")
|
||||
@ -64,13 +64,10 @@ init_app(app)
|
||||
# def get_locale():
|
||||
# return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
|
||||
|
||||
from . import models, tasks, template_filters
|
||||
|
||||
from . import models, tasks, template_filters, usermgr
|
||||
from .blueprints import create_blueprints
|
||||
create_blueprints(app)
|
||||
|
||||
from flask_login import logout_user
|
||||
|
||||
@app.route("/uploads/<path:path>")
|
||||
def send_upload(path):
|
||||
return send_from_directory(app.config['UPLOAD_DIR'], path)
|
||||
@ -88,7 +85,7 @@ def check_for_ban():
|
||||
if current_user.rank == models.UserRank.BANNED:
|
||||
flash("You have been banned.", "danger")
|
||||
logout_user()
|
||||
return redirect(url_for('user.login'))
|
||||
return redirect(url_for('users.login'))
|
||||
elif current_user.rank == models.UserRank.NOT_JOINED:
|
||||
current_user.rank = models.UserRank.MEMBER
|
||||
models.db.session.commit()
|
||||
|
@ -19,7 +19,7 @@ import os
|
||||
|
||||
from celery import group
|
||||
from flask import *
|
||||
from flask_user import *
|
||||
from flask_login import current_user
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import *
|
||||
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
|
||||
from flask import *
|
||||
from flask_user import *
|
||||
from flask_login import current_user, login_required
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import *
|
||||
from wtforms.validators import *
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
|
||||
from flask import *
|
||||
from flask_user import *
|
||||
from flask_login import current_user, login_required
|
||||
from . import bp
|
||||
from .auth import is_api_authd
|
||||
from .support import error, handleCreateRelease
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
|
||||
from flask import render_template, redirect, request, session, url_for, abort
|
||||
from flask_user import login_required, current_user
|
||||
from flask_login import login_required, current_user
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import *
|
||||
from wtforms.ext.sqlalchemy.fields import QuerySelectField
|
||||
|
@ -19,7 +19,7 @@ from flask import Blueprint
|
||||
bp = Blueprint("github", __name__)
|
||||
|
||||
from flask import redirect, url_for, request, flash, abort, render_template, jsonify, current_app
|
||||
from flask_user import current_user, login_required
|
||||
from flask_login import current_user, login_required
|
||||
from sqlalchemy import func, or_, and_
|
||||
from app import github, csrf
|
||||
from app.models import db, User, APIToken, Package, Permission
|
||||
@ -46,7 +46,7 @@ def callback(oauth_token):
|
||||
next_url = request.args.get("next")
|
||||
if oauth_token is None:
|
||||
flash("Authorization failed [err=gh-oauth-login-failed]", "danger")
|
||||
return redirect(url_for("user.login"))
|
||||
return redirect(url_for("users.login"))
|
||||
|
||||
# Get Github username
|
||||
url = "https://api.github.com/user"
|
||||
@ -79,7 +79,7 @@ def callback(oauth_token):
|
||||
return redirect(next_url or url_for("homepage.home"))
|
||||
else:
|
||||
flash("Authorization failed [err=gh-login-failed]", "danger")
|
||||
return redirect(url_for("user.login"))
|
||||
return redirect(url_for("users.login"))
|
||||
|
||||
|
||||
@bp.route("/github/webhook/", methods=["POST"])
|
||||
|
@ -16,10 +16,11 @@
|
||||
|
||||
|
||||
from flask import *
|
||||
from sqlalchemy import func
|
||||
from app.models import MetaPackage, Package, db, Dependency, PackageState, ForumTopic
|
||||
|
||||
bp = Blueprint("metapackages", __name__)
|
||||
|
||||
from app.models import *
|
||||
|
||||
@bp.route("/metapackages/")
|
||||
def list_all():
|
||||
@ -29,6 +30,7 @@ def list_all():
|
||||
.group_by(MetaPackage.id).all()
|
||||
return render_template("metapackages/list.html", mpackages=mpackages)
|
||||
|
||||
|
||||
@bp.route("/metapackages/<name>/")
|
||||
def view(name):
|
||||
mpackage = MetaPackage.query.filter_by(name=name).first()
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
|
||||
from flask import Blueprint, render_template, redirect, url_for
|
||||
from flask_user import current_user, login_required
|
||||
from flask_login import current_user, login_required
|
||||
from app.models import db, Notification
|
||||
|
||||
bp = Blueprint("notifications", __name__)
|
||||
|
@ -21,6 +21,7 @@ import flask_menu as menu
|
||||
from celery import uuid
|
||||
from flask import render_template
|
||||
from flask_wtf import FlaskForm
|
||||
from flask_login import login_required
|
||||
from sqlalchemy import or_, func
|
||||
from sqlalchemy.orm import joinedload, subqueryload
|
||||
from wtforms import *
|
||||
|
@ -18,6 +18,7 @@
|
||||
from celery import uuid
|
||||
from flask import *
|
||||
from flask_wtf import FlaskForm
|
||||
from flask_login import login_required
|
||||
from wtforms import *
|
||||
from wtforms.ext.sqlalchemy.fields import QuerySelectField
|
||||
from wtforms.validators import *
|
||||
|
@ -17,7 +17,7 @@
|
||||
from . import bp
|
||||
|
||||
from flask import *
|
||||
from flask_user import *
|
||||
from flask_login import current_user, login_required
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import *
|
||||
from wtforms.validators import *
|
||||
|
@ -17,6 +17,7 @@
|
||||
|
||||
from flask import *
|
||||
from flask_wtf import FlaskForm
|
||||
from flask_login import login_required
|
||||
from wtforms import *
|
||||
from wtforms.validators import *
|
||||
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
|
||||
from flask import *
|
||||
from flask_login import login_required
|
||||
|
||||
from app import csrf
|
||||
from app.tasks import celery
|
||||
|
@ -19,7 +19,7 @@ from flask import *
|
||||
|
||||
bp = Blueprint("threads", __name__)
|
||||
|
||||
from flask_user import *
|
||||
from flask_login import current_user, login_required
|
||||
from app.models import *
|
||||
from app.utils import addNotification, isYes, addAuditLog
|
||||
|
||||
|
@ -15,7 +15,7 @@
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
from flask import *
|
||||
from flask_user import *
|
||||
from flask_login import current_user, login_required
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.models import *
|
||||
|
@ -2,4 +2,4 @@ from flask import Blueprint
|
||||
|
||||
bp = Blueprint("users", __name__)
|
||||
|
||||
from . import profile, claim
|
||||
from . import profile, claim, account
|
||||
|
167
app/blueprints/users/account.py
Normal file
167
app/blueprints/users/account.py
Normal file
@ -0,0 +1,167 @@
|
||||
# ContentDB
|
||||
# Copyright (C) 2020 rubenwardy
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from flask import *
|
||||
from flask_login import current_user, login_required, logout_user, login_user
|
||||
from flask_wtf import FlaskForm
|
||||
from sqlalchemy import or_
|
||||
from wtforms import *
|
||||
from wtforms.validators import *
|
||||
|
||||
from app.models import *
|
||||
from app.tasks.emails import sendVerifyEmail
|
||||
from app.utils import randomString, make_flask_login_password, is_safe_url, check_password_hash
|
||||
from . import bp
|
||||
|
||||
|
||||
class LoginForm(FlaskForm):
|
||||
username = StringField("Username or email", [InputRequired()])
|
||||
password = PasswordField("Password", [InputRequired(), Length(6, 100)])
|
||||
remember_me = BooleanField("Remember me")
|
||||
submit = SubmitField("Login")
|
||||
|
||||
|
||||
@bp.route("/user/login/", methods=["GET", "POST"])
|
||||
def login():
|
||||
form = LoginForm(request.form)
|
||||
if form.validate_on_submit():
|
||||
username = form.username.data.strip()
|
||||
user = User.query.filter(or_(User.username==username, User.email==username)).first()
|
||||
if user is None:
|
||||
err = "User {} does not exist".format(username)
|
||||
|
||||
elif not check_password_hash(user.password, form.password.data):
|
||||
err = "Incorrect password. Did you set one?"
|
||||
|
||||
else:
|
||||
login_user(user)
|
||||
flash("Logged in successfully.")
|
||||
|
||||
next = request.args.get("r")
|
||||
if next and not is_safe_url(next):
|
||||
abort(400)
|
||||
|
||||
return redirect(next or url_for("homepage.home"))
|
||||
|
||||
if err:
|
||||
# The existence of a username is public, but emails are not
|
||||
if "@" in username:
|
||||
flash("Incorrect email or password", "danger")
|
||||
else:
|
||||
flash(err, "error")
|
||||
|
||||
|
||||
return render_template("users/login.html", form=form)
|
||||
|
||||
|
||||
@bp.route("/user/logout/", methods=["GET", "POST"])
|
||||
def logout():
|
||||
logout_user()
|
||||
return redirect(url_for("homepage.home"))
|
||||
|
||||
|
||||
class RegisterForm(FlaskForm):
|
||||
username = StringField("Username", [InputRequired()])
|
||||
email = StringField("Email", [InputRequired(), Email()])
|
||||
password = PasswordField("Password", [InputRequired(), Length(6, 100)])
|
||||
submit = SubmitField("Register")
|
||||
|
||||
|
||||
@bp.route("/user/register/", methods=["GET", "POST"])
|
||||
def register():
|
||||
form = RegisterForm(request.form)
|
||||
return render_template("users/register.html", form=form)
|
||||
|
||||
|
||||
@bp.route("/user/forgot-password/", methods=["GET", "POST"])
|
||||
def forgot_password():
|
||||
return "Forgot password page"
|
||||
|
||||
|
||||
class SetPasswordForm(FlaskForm):
|
||||
email = StringField("Email", [Optional(), Email()])
|
||||
password = PasswordField("New password", [InputRequired(), Length(8, 100)])
|
||||
password2 = PasswordField("Verify password", [InputRequired(), Length(8, 100)])
|
||||
submit = SubmitField("Save")
|
||||
|
||||
|
||||
@bp.route("/user/change-password/", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def change_password():
|
||||
return "change"
|
||||
|
||||
|
||||
@bp.route("/user/set-password/", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def set_password():
|
||||
if current_user.hasPassword():
|
||||
return redirect(url_for("users.change_password"))
|
||||
|
||||
form = SetPasswordForm(request.form)
|
||||
if current_user.email is None:
|
||||
form.email.validators = [InputRequired(), Email()]
|
||||
|
||||
if request.method == "POST" and form.validate():
|
||||
one = form.password.data
|
||||
two = form.password2.data
|
||||
if one == two:
|
||||
# Hash password
|
||||
hashed_password = make_flask_login_password(form.password.data)
|
||||
|
||||
# Change password
|
||||
current_user.password = hashed_password
|
||||
db.session.commit()
|
||||
|
||||
# Prepare one-time system message
|
||||
flash('Your password has been changed successfully.', 'success')
|
||||
|
||||
newEmail = form["email"].data
|
||||
if newEmail != current_user.email and newEmail.strip() != "":
|
||||
token = randomString(32)
|
||||
|
||||
ver = UserEmailVerification()
|
||||
ver.user = current_user
|
||||
ver.token = token
|
||||
ver.email = newEmail
|
||||
db.session.add(ver)
|
||||
db.session.commit()
|
||||
|
||||
task = sendVerifyEmail.delay(newEmail, token)
|
||||
return redirect(url_for("tasks.check", id=task.id, r=url_for("users.profile", username=current_user.username)))
|
||||
else:
|
||||
return redirect(url_for("users.login"))
|
||||
else:
|
||||
flash("Passwords do not match", "danger")
|
||||
|
||||
return render_template("users/set_password.html", form=form, optional=request.args.get("optional"))
|
||||
|
||||
|
||||
@bp.route("/users/verify/")
|
||||
def verify_email():
|
||||
token = request.args.get("token")
|
||||
ver = UserEmailVerification.query.filter_by(token=token).first()
|
||||
if ver is None:
|
||||
flash("Unknown verification token!", "danger")
|
||||
else:
|
||||
ver.user.email = ver.email
|
||||
db.session.delete(ver)
|
||||
db.session.commit()
|
||||
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("users.profile", username=current_user.username))
|
||||
else:
|
||||
return redirect(url_for("homepage.home"))
|
@ -16,7 +16,7 @@
|
||||
|
||||
|
||||
from flask import *
|
||||
from flask_user import signals, current_user, user_manager, login_required
|
||||
from flask_login import current_user, login_required
|
||||
from flask_wtf import FlaskForm
|
||||
from sqlalchemy import func
|
||||
from wtforms import *
|
||||
@ -26,7 +26,7 @@ from app.markdown import render_markdown
|
||||
from app.models import *
|
||||
from app.tasks.emails import sendVerifyEmail, sendEmailRaw
|
||||
from app.tasks.forumtasks import checkForumAccount
|
||||
from app.utils import randomString, rank_required, nonEmptyOrNone, addAuditLog
|
||||
from app.utils import randomString, rank_required, nonEmptyOrNone, addAuditLog, make_flask_login_password
|
||||
from . import bp
|
||||
|
||||
|
||||
@ -182,79 +182,3 @@ def send_email(username):
|
||||
return redirect(url_for("tasks.check", id=task.id, r=next_url))
|
||||
|
||||
return render_template("users/send_email.html", form=form)
|
||||
|
||||
|
||||
|
||||
class SetPasswordForm(FlaskForm):
|
||||
email = StringField("Email", [Optional(), Email()])
|
||||
password = PasswordField("New password", [InputRequired(), Length(2, 100)])
|
||||
password2 = PasswordField("Verify password", [InputRequired(), Length(2, 100)])
|
||||
submit = SubmitField("Save")
|
||||
|
||||
@bp.route("/user/set-password/", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def set_password():
|
||||
if current_user.hasPassword():
|
||||
return redirect(url_for("user.change_password"))
|
||||
|
||||
form = SetPasswordForm(request.form)
|
||||
if current_user.email is None:
|
||||
form.email.validators = [InputRequired(), Email()]
|
||||
|
||||
if request.method == "POST" and form.validate():
|
||||
one = form.password.data
|
||||
two = form.password2.data
|
||||
if one == two:
|
||||
# Hash password
|
||||
hashed_password = user_manager.hash_password(form.password.data)
|
||||
|
||||
# Change password
|
||||
current_user.password = hashed_password
|
||||
db.session.commit()
|
||||
|
||||
# Send 'password_changed' email
|
||||
if user_manager.USER_ENABLE_EMAIL and current_user.email:
|
||||
user_manager.email_manager.send_password_changed_email(current_user)
|
||||
|
||||
# Send password_changed signal
|
||||
signals.user_changed_password.send(current_app._get_current_object(), user=current_user)
|
||||
|
||||
# Prepare one-time system message
|
||||
flash('Your password has been changed successfully.', 'success')
|
||||
|
||||
newEmail = form["email"].data
|
||||
if newEmail != current_user.email and newEmail.strip() != "":
|
||||
token = randomString(32)
|
||||
|
||||
ver = UserEmailVerification()
|
||||
ver.user = current_user
|
||||
ver.token = token
|
||||
ver.email = newEmail
|
||||
db.session.add(ver)
|
||||
db.session.commit()
|
||||
|
||||
task = sendVerifyEmail.delay(newEmail, token)
|
||||
return redirect(url_for("tasks.check", id=task.id, r=url_for("users.profile", username=current_user.username)))
|
||||
else:
|
||||
return redirect(url_for("user.login"))
|
||||
else:
|
||||
flash("Passwords do not match", "danger")
|
||||
|
||||
return render_template("users/set_password.html", form=form, optional=request.args.get("optional"))
|
||||
|
||||
|
||||
@bp.route("/users/verify/")
|
||||
def verify_email():
|
||||
token = request.args.get("token")
|
||||
ver = UserEmailVerification.query.filter_by(token=token).first()
|
||||
if ver is None:
|
||||
flash("Unknown verification token!", "danger")
|
||||
else:
|
||||
ver.user.email = ver.email
|
||||
db.session.delete(ver)
|
||||
db.session.commit()
|
||||
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("users.profile", username=current_user.username))
|
||||
else:
|
||||
return redirect(url_for("homepage.home"))
|
||||
|
@ -1,11 +1,11 @@
|
||||
from .models import *
|
||||
from .utils import make_flask_user_password
|
||||
from .utils import make_flask_login_password
|
||||
|
||||
|
||||
def populate(session):
|
||||
admin_user = User("rubenwardy")
|
||||
admin_user.active = True
|
||||
admin_user.password = make_flask_user_password("tuckfrump")
|
||||
admin_user.is_active = True
|
||||
admin_user.password = make_flask_login_password("tuckfrump")
|
||||
admin_user.github_username = "rubenwardy"
|
||||
admin_user.forums_username = "rubenwardy"
|
||||
admin_user.rank = UserRank.ADMIN
|
||||
|
@ -22,11 +22,11 @@ from urllib.parse import urlparse
|
||||
from flask import url_for
|
||||
from flask_migrate import Migrate
|
||||
from flask_sqlalchemy import SQLAlchemy, BaseQuery
|
||||
from flask_user import UserManager, UserMixin
|
||||
from sqlalchemy_searchable import SearchQueryMixin, make_searchable
|
||||
from sqlalchemy_utils.types import TSVectorType
|
||||
|
||||
from app import app, gravatar
|
||||
from .usermgr import UserMixin, login_manager
|
||||
from . import app, gravatar
|
||||
|
||||
# Initialise database
|
||||
db = SQLAlchemy(app)
|
||||
@ -138,6 +138,9 @@ class User(db.Model, UserMixin):
|
||||
password = db.Column(db.String(255), nullable=False, server_default="")
|
||||
reset_password_token = db.Column(db.String(100), nullable=False, server_default="")
|
||||
|
||||
def get_id(self):
|
||||
return self.username
|
||||
|
||||
rank = db.Column(db.Enum(UserRank))
|
||||
|
||||
# Account linking
|
||||
@ -153,7 +156,7 @@ class User(db.Model, UserMixin):
|
||||
|
||||
# User information
|
||||
profile_pic = db.Column(db.String(255), nullable=True, server_default=None)
|
||||
active = db.Column("is_active", db.Boolean, nullable=False, server_default="0")
|
||||
is_active = db.Column("is_active", db.Boolean, nullable=False, server_default="0")
|
||||
display_name = db.Column(db.String(100), nullable=False, default=display_name_default)
|
||||
|
||||
# Links
|
||||
@ -174,7 +177,7 @@ class User(db.Model, UserMixin):
|
||||
self.username = username
|
||||
self.email_confirmed_at = datetime.datetime.now() - datetime.timedelta(days=6000)
|
||||
self.display_name = username
|
||||
self.active = active
|
||||
self.is_active = active
|
||||
self.email = email
|
||||
self.password = password
|
||||
self.rank = UserRank.NOT_JOINED
|
||||
@ -718,7 +721,7 @@ class Package(db.Model):
|
||||
|
||||
def getSetStateURL(self, state):
|
||||
if type(state) == str:
|
||||
state = PackageState[perm]
|
||||
state = PackageState[state]
|
||||
elif type(state) != PackageState:
|
||||
raise Exception("Unknown state given to Package.canMoveToState()")
|
||||
|
||||
@ -1474,10 +1477,11 @@ class ForumTopic(db.Model):
|
||||
raise Exception("Permission {} is not related to topics".format(perm.name))
|
||||
|
||||
|
||||
# Setup Flask-User
|
||||
user_manager = UserManager(app, db, User)
|
||||
|
||||
if app.config.get("LOG_SQL"):
|
||||
import logging
|
||||
logging.basicConfig()
|
||||
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id):
|
||||
return User.query.filter_by(username=user_id).first()
|
||||
|
@ -1,7 +1,7 @@
|
||||
from . import app
|
||||
from .models import Permission, Package, PackageState, PackageRelease
|
||||
from .utils import abs_url_for, url_set_query
|
||||
from flask_user import current_user
|
||||
from flask_login import current_user
|
||||
from flask_babel import format_timedelta
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
@ -131,11 +131,11 @@
|
||||
<li class="nav-item"><a class="nav-link" href="{{ url_for('admin.license_list') }}">{{ _("License Editor") }}</a></li>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<li class="nav-item"><a class="nav-link" href="{{ url_for('user.logout') }}">{{ _("Sign out") }}</a></li>
|
||||
<li class="nav-item"><a class="nav-link" href="{{ url_for('users.logout') }}">{{ _("Sign out") }}</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
{% else %}
|
||||
<li><a class="nav-link" href="{{ url_for('user.login') }}">{{ _("Sign in") }}</a></li>
|
||||
<li><a class="nav-link" href="{{ url_for('users.login') }}">{{ _("Sign in") }}</a></li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</div>
|
||||
|
@ -126,7 +126,7 @@ Creating an Account
|
||||
options.
|
||||
</p>
|
||||
|
||||
<a class="btn btn-primary" href="{{ url_for('user.register') }}">Register</a>
|
||||
<a class="btn btn-primary" href="{{ url_for('users.register') }}">Register</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -8,33 +8,21 @@ Sign in
|
||||
<div class="row">
|
||||
<div class="col-sm-8">
|
||||
<div class="card">
|
||||
{% from "flask_user/_macros.html" import render_field, render_checkbox_field, render_submit_field %}
|
||||
{% from "macros/forms.html" import render_field, render_checkbox_field, render_submit_field %}
|
||||
<h2 class="card-header">{%trans%}Sign in{%endtrans%}</h2>
|
||||
|
||||
<form action="" method="POST" class="form card-body" role="form">
|
||||
{{ form.hidden_tag() }}
|
||||
|
||||
{# Username or Email field #}
|
||||
{% set field = form.username if user_manager.USER_ENABLE_USERNAME else form.email %}
|
||||
<div class="form-group {% if field.errors %}has-error{% endif %}">
|
||||
{# Label on left, "New here? Register." on right #}
|
||||
<label for="{{ field.id }}" class="control-label">{{ field.label.text }}</label>
|
||||
{{ field(class_='form-control', tabindex=110) }}
|
||||
{% if field.errors %}
|
||||
{% for e in field.errors %}
|
||||
<p class="help-block">{{ e }}</p>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</div>
|
||||
{{ render_field(form.username) }}
|
||||
|
||||
{# Password field #}
|
||||
{% set field = form.password %}
|
||||
<div class="form-group {% if field.errors %}has-error{% endif %}">
|
||||
<label for="{{ field.id }}" class="control-label">{{ field.label.text }}
|
||||
{% if user_manager.USER_ENABLE_FORGOT_PASSWORD %}
|
||||
<a href="{{ url_for('user.forgot_password') }}" tabindex='195'>
|
||||
[{%trans%}Forgot My Password{%endtrans%}]</a>
|
||||
{% endif %}
|
||||
<a href="{{ url_for('users.forgot_password') }}" tabindex='195'>
|
||||
[{%trans%}Forgot my password{%endtrans%}]</a>
|
||||
</label>
|
||||
{{ field(class_='form-control', tabindex=120) }}
|
||||
{% if field.errors %}
|
||||
@ -45,9 +33,7 @@ Sign in
|
||||
</div>
|
||||
|
||||
{# Remember me #}
|
||||
{% if user_manager.USER_ENABLE_REMEMBER_ME %}
|
||||
{{ render_checkbox_field(login_form.remember_me, tabindex=130) }}
|
||||
{% endif %}
|
||||
{{ render_checkbox_field(form.remember_me, tabindex=130) }}
|
||||
|
||||
{# Submit button #}
|
||||
<p>
|
||||
@ -57,7 +43,6 @@ Sign in
|
||||
</div>
|
||||
|
||||
<div class="card mt-4">
|
||||
{% from "flask_user/_macros.html" import render_field, render_checkbox_field, render_submit_field %}
|
||||
<h2 class="card-header">{%trans%}Sign in with Github{%endtrans%}</h2>
|
||||
<div class="card-body">
|
||||
<a class="btn btn-primary" href="{{ url_for('github.start') }}">GitHub</a>
|
||||
@ -67,7 +52,6 @@ Sign in
|
||||
|
||||
<aside class="col-sm-4">
|
||||
<div class="card">
|
||||
{% from "flask_user/_macros.html" import render_field, render_checkbox_field, render_submit_field %}
|
||||
<h2 class="card-header">{%trans%}New here?{%endtrans%}</h2>
|
||||
<div class="card-body">
|
||||
<p>Create an account using your forum account or email.</p>
|
@ -132,7 +132,7 @@
|
||||
<td>Password:</td>
|
||||
<td>
|
||||
{% if user.password %}
|
||||
Set | <a href="{{ url_for('user.change_password') }}">Change</a>
|
||||
Set | <a href="{{ url_for('users.change_password') }}">Change</a>
|
||||
{% else %}
|
||||
Not set | <a href="{{ url_for('users.set_password') }}">Set</a>
|
||||
{% endif %}
|
||||
|
31
app/templates/users/register.html
Normal file
31
app/templates/users/register.html
Normal file
@ -0,0 +1,31 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
Register
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% from "macros/forms.html" import render_field, render_checkbox_field, render_submit_field %}
|
||||
|
||||
<div class="card">
|
||||
<h2 class="card-header">{{ _("Register") }}</h2>
|
||||
|
||||
<form action="" method="POST" class="form card-body" role="form">
|
||||
{{ form.hidden_tag() }}
|
||||
|
||||
{{ render_field(form.username) }}
|
||||
{{ render_field(form.email) }}
|
||||
{{ render_field(form.password) }}
|
||||
|
||||
<p>
|
||||
Must be at least 8 characters long.
|
||||
</p>
|
||||
|
||||
{# Submit button #}
|
||||
<p>
|
||||
{{ render_submit_field(form.submit, tabindex=180) }}
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
10
app/usermgr.py
Normal file
10
app/usermgr.py
Normal file
@ -0,0 +1,10 @@
|
||||
from . import app
|
||||
from flask_login import LoginManager
|
||||
|
||||
login_manager = LoginManager()
|
||||
login_manager.init_app(app)
|
||||
login_manager.login_view = "users.login"
|
||||
|
||||
class UserMixin:
|
||||
is_authenticated = True
|
||||
is_anonymous = False
|
54
app/utils.py
54
app/utils.py
@ -19,18 +19,25 @@ import imghdr
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import user_agents
|
||||
from functools import wraps
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import user_agents
|
||||
from flask import request, flash, abort, redirect
|
||||
from flask_login import login_user
|
||||
from flask_user import *
|
||||
from flask_login import login_user, current_user
|
||||
from werkzeug.datastructures import MultiDict
|
||||
from passlib.hash import bcrypt
|
||||
|
||||
from . import app
|
||||
from .models import *
|
||||
|
||||
|
||||
def is_safe_url(target):
|
||||
ref_url = urlparse(request.host_url)
|
||||
test_url = urlparse(urljoin(request.host_url, target))
|
||||
return test_url.scheme in ('http', 'https') and \
|
||||
ref_url.netloc == test_url.netloc
|
||||
|
||||
|
||||
# These are given to Jinja in template_filters.py
|
||||
|
||||
def abs_url_for(path, **kwargs):
|
||||
@ -130,28 +137,17 @@ def doFileUpload(file, fileType, fileTypeDesc):
|
||||
file.save(filepath)
|
||||
return "/uploads/" + filename, filepath
|
||||
|
||||
def make_flask_user_password(plaintext_str):
|
||||
# http://passlib.readthedocs.io/en/stable/modular_crypt_format.html
|
||||
# http://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#format-algorithm
|
||||
# Flask_User stores passwords in the Modular Crypt Format.
|
||||
# https://github.com/lingthio/Flask-User/blob/master/flask_user/user_manager__settings.py#L166
|
||||
# Note that Flask_User allows customizing password algorithms.
|
||||
# USER_PASSLIB_CRYPTCONTEXT_SCHEMES defaults to bcrypt but if
|
||||
# default changes or is customized, the code below needs adapting.
|
||||
# Individual password values will look like:
|
||||
# $2b$12$.az4S999Ztvy/wa3UdQvMOpcki1Qn6VYPXmEFMIdWQyYs7ULnH.JW
|
||||
# $XX$RR$SSSSSSSSSSSSSSSSSSSSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
|
||||
# $XX : Selects algorithm (2b is bcrypt).
|
||||
# $RR : Selects bcrypt key expansion rounds (12 is 2**12 rounds).
|
||||
# $SSS... : 22 chars of (random, per-password) salt
|
||||
# HHH... : 31 remaining chars of password hash (note no dollar sign)
|
||||
import bcrypt
|
||||
plaintext = plaintext_str.encode("UTF-8")
|
||||
password = bcrypt.hashpw(plaintext, bcrypt.gensalt())
|
||||
if isinstance(password, str):
|
||||
return password
|
||||
else:
|
||||
return password.decode("UTF-8")
|
||||
|
||||
def check_password_hash(stored, given):
|
||||
if stored is None or stored == "":
|
||||
return False
|
||||
|
||||
return bcrypt.verify(given.encode("UTF-8"), stored)
|
||||
|
||||
|
||||
def make_flask_login_password(plaintext):
|
||||
return bcrypt.hash(plaintext.encode("UTF-8"))
|
||||
|
||||
|
||||
def loginUser(user):
|
||||
def _call_or_get(v):
|
||||
@ -168,7 +164,7 @@ def loginUser(user):
|
||||
flash("You have been banned.", "danger")
|
||||
return False
|
||||
|
||||
user.active = True
|
||||
user.is_active = True
|
||||
if not user.rank.atLeast(UserRank.NEW_MEMBER):
|
||||
user.rank = UserRank.MEMBER
|
||||
|
||||
@ -179,9 +175,7 @@ def loginUser(user):
|
||||
flash("Your account has not been enabled.", "danger")
|
||||
return False
|
||||
|
||||
# Use Flask-Login to sign in user
|
||||
login_user(user, remember=True)
|
||||
signals.user_logged_in.send(current_app._get_current_object(), user=user)
|
||||
|
||||
flash("You have signed in successfully.", "success")
|
||||
|
||||
@ -193,7 +187,7 @@ def rank_required(rank):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for("user.login"))
|
||||
return redirect(url_for("users.login"))
|
||||
if not current_user.rank.atLeast(rank):
|
||||
abort(403)
|
||||
|
||||
|
@ -15,11 +15,6 @@ REDIS_URL = 'redis://redis:6379'
|
||||
CELERY_BROKER_URL = 'redis://redis:6379'
|
||||
CELERY_RESULT_BACKEND = 'redis://redis:6379'
|
||||
|
||||
USER_ENABLE_USERNAME = True
|
||||
USER_ENABLE_REGISTER = False
|
||||
USER_ENABLE_CHANGE_USERNAME = False
|
||||
|
||||
USER_ENABLE_EMAIL = False
|
||||
MAIL_USERNAME = ""
|
||||
MAIL_PASSWORD = ""
|
||||
USER_EMAIL_SENDER_NAME = ""
|
||||
|
@ -26,7 +26,6 @@ Flask-Mail==0.9.1
|
||||
Flask-Menu==0.7.2
|
||||
Flask-Migrate==2.5.3
|
||||
Flask-SQLAlchemy==2.4.4
|
||||
Flask-User==1.0.2.2
|
||||
Flask-WTF==0.14.3
|
||||
future==0.18.2
|
||||
git-archive-all==1.21.0
|
||||
|
@ -5,7 +5,6 @@ Flask-Login ~= 0.5
|
||||
Flask-Menu ~= 0.7
|
||||
Flask-Migrate ~= 2.3
|
||||
Flask-SQLAlchemy ~= 2.3
|
||||
Flask-User ~= 1.0
|
||||
Flask-Babel
|
||||
GitHub-Flask ~= 3.2
|
||||
SQLAlchemy-Searchable ~= 1.1
|
||||
@ -32,3 +31,9 @@ email_validator
|
||||
pyyaml
|
||||
ua-parser
|
||||
user-agents
|
||||
|
||||
Werkzeug~=0.16.0
|
||||
WTForms~=2.2.1
|
||||
SQLAlchemy~=1.3.12
|
||||
requests~=2.22.0
|
||||
alembic~=1.3.2
|
||||
|
Loading…
Reference in New Issue
Block a user