refactor in a module register

This commit is contained in:
Cayo Puigdefabregas 2022-10-27 20:10:08 +02:00
parent 7041bfcf76
commit 4bbec903ef
11 changed files with 190 additions and 154 deletions

View File

@ -1,13 +1,10 @@
from flask import current_app as app from flask import g
from flask import g, render_template
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from werkzeug.security import generate_password_hash from werkzeug.security import generate_password_hash
from wtforms import BooleanField, EmailField, PasswordField, StringField, validators from wtforms import BooleanField, EmailField, PasswordField, validators
from ereuse_devicehub.db import db from ereuse_devicehub.db import db
from ereuse_devicehub.mail.sender import send_email from ereuse_devicehub.resources.user.models import User
from ereuse_devicehub.resources.agent.models import Person
from ereuse_devicehub.resources.user.models import User, UserValidation
class LoginForm(FlaskForm): class LoginForm(FlaskForm):
@ -104,108 +101,3 @@ class PasswordForm(FlaskForm):
if commit: if commit:
db.session.commit() db.session.commit()
return return
class UserNewRegisterForm(FlaskForm):
email = EmailField(
'Email Address', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
password = PasswordField(
'Password', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
password2 = PasswordField(
'Password', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
name = StringField(
'Name', [validators.DataRequired(), validators.Length(min=3, max=35)]
)
error_messages = {
'invalid_login': (
"Please enter a correct email and password. Note that both "
"fields may be case-sensitive."
),
'inactive': "This account is inactive.",
}
def validate(self, extra_validators=None):
is_valid = super().validate(extra_validators)
if not is_valid:
return False
email = self.email.data
password = self.password.data
password2 = self.password2.data
if password != password2:
self.form_errors.append('The passwords are not equal.')
return False
txt = 'This email are in use.'
email = self.email.data
if User.query.filter_by(email=email).first():
self.form_errors.append(txt)
return False
self.email.data = self.email.data.strip()
self.password.data = self.password.data.strip()
return True
def save(self, commit=True):
user_validation = self.new_user()
if commit:
db.session.commit()
self._token = user_validation.token
self.send_mail()
self.send_mail_admin(user_validation.user)
def new_user(self):
user = User(email=self.email.data, password=self.password.data, active=False)
person = Person(
email=self.email.data,
name=self.name.data,
)
user.individuals.add(person)
db.session.add(user)
user_validation = UserValidation(
user=user,
)
db.session.add(user_validation)
return user_validation
def send_mail(self):
host = app.config.get('HOST')
token = self._token
url = f'https://{ host }/validate_user/{ token }'
template = 'ereuse_devicehub/email_validation.txt'
template_html = 'ereuse_devicehub/email_validation.html'
context = {
'name': self.name.data,
'host': host,
'url': url,
}
subject = "Please activate your Usody account"
message = render_template(template, **context)
message_html = render_template(template_html, **context)
send_email(subject, [self.email.data], message, html_body=message_html)
def send_mail_admin(self, user):
person = next(iter(user.individuals))
context = {
'email': person.email,
'name': person.name,
}
template = 'ereuse_devicehub/email_admin_new_user.txt'
message = render_template(template, **context)
subject = "New Register"
email_admin = app.config.get("EMAIL_ADMIN")
if email_admin:
send_email(subject, [email_admin], message)

View File

View File

@ -0,0 +1,114 @@
from flask import current_app as app
from flask import render_template
from flask_wtf import FlaskForm
from wtforms import EmailField, PasswordField, StringField, validators
from ereuse_devicehub.db import db
from ereuse_devicehub.mail.sender import send_email
from ereuse_devicehub.resources.agent.models import Person
from ereuse_devicehub.resources.user.models import User, UserValidation
class UserNewRegisterForm(FlaskForm):
email = EmailField(
'Email Address', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
password = PasswordField(
'Password', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
password2 = PasswordField(
'Password', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
name = StringField(
'Name', [validators.DataRequired(), validators.Length(min=3, max=35)]
)
error_messages = {
'invalid_login': (
"Please enter a correct email and password. Note that both "
"fields may be case-sensitive."
),
'inactive': "This account is inactive.",
}
def validate(self, extra_validators=None):
is_valid = super().validate(extra_validators)
if not is_valid:
return False
email = self.email.data
password = self.password.data
password2 = self.password2.data
if password != password2:
self.form_errors.append('The passwords are not equal.')
return False
txt = 'This email are in use.'
email = self.email.data
if User.query.filter_by(email=email).first():
self.form_errors.append(txt)
return False
self.email.data = self.email.data.strip()
self.password.data = self.password.data.strip()
return True
def save(self, commit=True):
user_validation = self.new_user()
if commit:
db.session.commit()
self._token = user_validation.token
self.send_mail()
self.send_mail_admin(user_validation.user)
def new_user(self):
user = User(email=self.email.data, password=self.password.data, active=False)
person = Person(
email=self.email.data,
name=self.name.data,
)
user.individuals.add(person)
db.session.add(user)
user_validation = UserValidation(
user=user,
)
db.session.add(user_validation)
return user_validation
def send_mail(self):
host = app.config.get('HOST')
token = self._token
url = f'https://{ host }/validate_user/{ token }'
template = 'registration/email_validation.txt'
template_html = 'registration/email_validation.html'
context = {
'name': self.name.data,
'host': host,
'url': url,
}
subject = "Please activate your Usody account"
message = render_template(template, **context)
message_html = render_template(template_html, **context)
send_email(subject, [self.email.data], message, html_body=message_html)
def send_mail_admin(self, user):
person = next(iter(user.individuals))
context = {
'email': person.email,
'name': person.name,
}
template = 'registration/email_admin_new_user.txt'
message = render_template(template, **context)
subject = "New Register"
email_admin = app.config.get("EMAIL_ADMIN")
if email_admin:
send_email(subject, [email_admin], message)

View File

@ -0,0 +1,9 @@
Welcome to Usody.com, {{ name }}!<br />
<br />
Please confirm your account by clicking on the following link:<br />
<a href="{{ url }}">{{ url }}</a><br />
<br />
<img src="https://{{ host }}{{ url_for('static', filename='img/usody_logo_transparent_noicon-y-purple-120x41.png') }}" alt="">
<br />
Plaça Eusebi Güell 6-7, Edifici Vèrtex (UPC), planta 0, Barcelona 08034, Spain<br />
Associació Pangea Coordinadora Comunicació per a la Cooperació - NIF: G-60437761

View File

@ -0,0 +1,50 @@
import flask
from flask import Blueprint
from flask.views import View
from ereuse_devicehub import __version__
from ereuse_devicehub.db import db
from ereuse_devicehub.register.forms import UserNewRegisterForm
from ereuse_devicehub.resources.user.models import UserValidation
register = Blueprint('register', __name__, template_folder='templates')
class UserRegistrationView(View):
methods = ['GET', 'POST']
template_name = 'registration/user_registration.html'
def dispatch_request(self):
form = UserNewRegisterForm()
if form.validate_on_submit():
form.save()
context = {'form': form, 'version': __version__}
return flask.render_template(self.template_name, **context)
class UserValidationView(View):
methods = ['GET']
template_name = 'registration/user_validation.html'
def dispatch_request(self, token):
context = {'is_valid': self.is_valid(token), 'version': __version__}
return flask.render_template(self.template_name, **context)
def is_valid(self, token):
user_valid = UserValidation.query.filter_by(token=token).first()
if not user_valid:
return False
user = user_valid.user
user.active = True
db.session.commit()
return True
register.add_url_rule(
'/new_register/',
view_func=UserRegistrationView.as_view('user-registration'),
)
register.add_url_rule(
'/validate_user/<uuid:token>',
view_func=UserValidationView.as_view('user-validation'),
)

View File

@ -61,7 +61,7 @@
<button class="btn btn-primary w-100" type="submit">Next</button> <button class="btn btn-primary w-100" type="submit">Next</button>
</div> </div>
<div class="col-12"> <div class="col-12">
<p class="small mb-0">Don't have account? <a href="{{ url_for('core.user-registration') }}">Create an account</a></p> <p class="small mb-0">Don't have account? <a href="{{ url_register }}">Create an account</a></p>
</div> </div>
</form> </form>

View File

@ -1,15 +1,17 @@
import flask import flask
from flask import Blueprint, g from flask import Blueprint
from flask import current_app as app
from flask import g
from flask.views import View from flask.views import View
from flask_login import current_user, login_required, login_user, logout_user from flask_login import current_user, login_required, login_user, logout_user
from sqlalchemy import or_ from sqlalchemy import or_
from ereuse_devicehub import __version__, messages from ereuse_devicehub import __version__, messages
from ereuse_devicehub.db import db from ereuse_devicehub.db import db
from ereuse_devicehub.forms import LoginForm, PasswordForm, UserNewRegisterForm from ereuse_devicehub.forms import LoginForm, PasswordForm
from ereuse_devicehub.resources.action.models import Trade from ereuse_devicehub.resources.action.models import Trade
from ereuse_devicehub.resources.lot.models import Lot from ereuse_devicehub.resources.lot.models import Lot
from ereuse_devicehub.resources.user.models import User, UserValidation from ereuse_devicehub.resources.user.models import User
from ereuse_devicehub.utils import is_safe_url from ereuse_devicehub.utils import is_safe_url
core = Blueprint('core', __name__) core = Blueprint('core', __name__)
@ -39,8 +41,14 @@ class LoginView(View):
return flask.abort(400) return flask.abort(400)
return flask.redirect(next_url or flask.url_for('inventory.devicelist')) return flask.redirect(next_url or flask.url_for('inventory.devicelist'))
context = {'form': form, 'version': __version__}
return flask.render_template('ereuse_devicehub/user_login.html', **context) url_register = "#"
if 'register' in app.blueprints.keys():
url_register = flask.url_for('register.user-registration')
context = {'form': form, 'version': __version__, 'url_register': url_register}
return flask.render_template(self.template_name, **context)
class LogoutView(View): class LogoutView(View):
@ -108,44 +116,7 @@ class UserPasswordView(View):
return flask.redirect(flask.url_for('core.user-profile')) return flask.redirect(flask.url_for('core.user-profile'))
class UserRegistrationView(View):
methods = ['GET', 'POST']
template_name = 'ereuse_devicehub/user_registration.html'
def dispatch_request(self):
form = UserNewRegisterForm()
if form.validate_on_submit():
form.save()
context = {'form': form, 'version': __version__}
return flask.render_template(self.template_name, **context)
class UserValidationView(View):
methods = ['GET']
template_name = 'ereuse_devicehub/user_validation.html'
def dispatch_request(self, token):
context = {'is_valid': self.is_valid(token), 'version': __version__}
return flask.render_template(self.template_name, **context)
def is_valid(self, token):
user_valid = UserValidation.query.filter_by(token=token).first()
if not user_valid:
return False
user = user_valid.user
user.active = True
db.session.commit()
return True
core.add_url_rule('/login/', view_func=LoginView.as_view('login')) core.add_url_rule('/login/', view_func=LoginView.as_view('login'))
core.add_url_rule('/logout/', view_func=LogoutView.as_view('logout')) core.add_url_rule('/logout/', view_func=LogoutView.as_view('logout'))
core.add_url_rule('/profile/', view_func=UserProfileView.as_view('user-profile')) core.add_url_rule('/profile/', view_func=UserProfileView.as_view('user-profile'))
core.add_url_rule(
'/new_register/', view_func=UserRegistrationView.as_view('user-registration')
)
core.add_url_rule(
'/validate_user/<uuid:token>',
view_func=UserValidationView.as_view('user-validation'),
)
core.add_url_rule('/set_password/', view_func=UserPasswordView.as_view('set-password')) core.add_url_rule('/set_password/', view_func=UserPasswordView.as_view('set-password'))