Merge pull request #400 from eReuse/bugfix/4046-drop-register-user

remove user_registration
This commit is contained in:
cayop 2022-11-08 18:12:56 +01:00 committed by GitHub
commit fe33f2d7e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 1 additions and 533 deletions

View File

@ -1,60 +0,0 @@
"""user validation
Revision ID: abba37ff5c80
Revises: d65745749e34
Create Date: 2022-09-30 10:01:19.761864
"""
import sqlalchemy as sa
from alembic import context, op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'abba37ff5c80'
down_revision = 'd65745749e34'
branch_labels = None
depends_on = None
def get_inv():
INV = context.get_x_argument(as_dictionary=True).get('inventory')
if not INV:
raise ValueError("Inventory value is not specified")
return INV
def upgrade():
op.create_table(
'user_validation',
sa.Column('id', sa.BigInteger(), nullable=False),
sa.Column(
'updated',
sa.TIMESTAMP(timezone=True),
server_default=sa.text('CURRENT_TIMESTAMP'),
nullable=False,
),
sa.Column(
'created',
sa.TIMESTAMP(timezone=True),
server_default=sa.text('CURRENT_TIMESTAMP'),
nullable=False,
),
sa.Column('joined_at', sa.TIMESTAMP(timezone=True), nullable=True),
sa.Column('expired', sa.BigInteger(), nullable=False),
sa.Column('token', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('user_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(
['user_id'],
['common.user.id'],
),
sa.UniqueConstraint('token'),
schema=f'{get_inv()}',
)
op.execute(f"CREATE SEQUENCE {get_inv()}.user_validation_seq;")
def downgrade():
op.drop_table('user_validation', schema=f'{get_inv()}')
op.execute(f"DROP SEQUENCE {get_inv()}.user_validation_seq;")

View File

@ -1,114 +0,0 @@
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

@ -1,4 +0,0 @@
A new user has been registered:
Name: {{ name }}
Email: {{ email }}

View File

@ -1,9 +0,0 @@
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

@ -1,7 +0,0 @@
Welcome to Usody.com, {{ name }}!
Please confirm your account by clicking on the following link: {{ url }}
--
Plaça Eusebi Güell 6-7, Edifici Vèrtex (UPC), planta 0, Barcelona 08034, Spain
Associació Pangea Coordinadora Comunicació per a la Cooperació - NIF: G-60437761

View File

@ -1,172 +0,0 @@
{% extends "ereuse_devicehub/base.html" %}
{% block page_title %}Create your account{% endblock %}
{% block body %}
<main>
<div class="container">
<section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center">
<div class="d-flex justify-content-center py-4">
<a href="{{ url_for('core.login') }}" class="d-flex align-items-center w-auto">
<img src="{{ url_for('static', filename='img/usody_logo_transparent_noicon-y-purple-120x41.png') }}" alt="">
</a>
</div><!-- End Logo -->
<div class="card mb-3">
<div class="card-body">
<div class="pt-4 pb-2">
<h5 class="card-title text-center pb-0 fs-4 help">Create your account</h5>
{% if not form._token %}
{% if form.form_errors %}
<p class="text-danger">
{% for error in form.form_errors %}
{{ error }}<br/>
{% endfor %}
</p>
{% endif %}
</div>
<form method="post" class="row g-3 needs-validation" novalidate>
{{ form.csrf_token }}
<div class="col-12">
<input name="name" class="form-control" placeholder="Name *" id="name" required>
{% if form.name.errors %}
<p class="text-danger">
{% for error in form.name.errors %}
{{ error }}<br/>
{% endfor %}
</p>
{% endif %}
</div>
<div class="col-12">
<input type="email" name="email" placeholder="Email *" class="form-control" id="email" required value="{{ form.email.data|default('', true) }}">
<div class="invalid-feedback">Please enter your email.</div>
{% if form.email.errors %}
<p class="text-danger">
{% for error in form.email.errors %}
{{ error }}<br/>
{% endfor %}
</p>
{% endif %}
</div>
<div class="col-12">
<div class="input-group">
<input type="password" name="password" placeholder="Password *" class="form-control" id="password" required>
<i class="input-group-text bi bi-eye" id="togglePassword" style="cursor: pointer"></i>
</div>
<div class="invalid-feedback">Please enter a password!</div>
{% if form.password.errors %}
<p class="text-danger">
{% for error in form.password.errors %}
{{ error }}<br/>
{% endfor %}
</p>
{% endif %}
</div>
<div class="col-12">
<div class="input-group">
<input type="password" name="password2" placeholder="Password *" class="form-control" id="password2" required>
<i class="input-group-text bi bi-eye" id="togglePassword2" style="cursor: pointer"></i>
</div>
<div class="invalid-feedback">Please enter a password again!</div>
{% if form.password2.errors %}
<p class="text-danger">
{% for error in form.password2.errors %}
{{ error }}<br/>
{% endfor %}
</p>
{% endif %}
</div>
<div class="col-12">
<small><i class="bi bi-info-circle"></i> Password must be at least 6 characters.</small>
</div>
<div class="col-12">
<input type="checkbox" name="policy" class="form-check-input" id="policy" required>
<span>I accept the
<a href="https://pangea.org/aviso-legal/" target="_blank">terms</a> and
<a href="https://pangea.org/es/politica-de-privacidad/" target="_blank">privacy policy</a>
</span>
</div>
<div class="col-12">
<button class="btn btn-primary w-100" type="submit">Next</button>
</div>
<div class="col-12">
<p class="small mb-0">
Already have an account? <a href="{{ url_for('core.login') }}">Sign in</a>
</p>
</div>
</form>
{% else %}
</div>
<div class="col-12 p-4 text-center">
We have sent you a validation email.<br />
Please check your email.
</div>
{% endif %}
</div>
</div>
<div class="credits">
<a href="https://help.usody.com/en/getting-started/introduction/" target="_blank">Help</a> |
<a href="https://pangea.org/es/politica-de-privacidad/" target="_blank">Privacy</a> |
<a href="https://pangea.org/aviso-legal/" target="_blank">Terms</a>
</div>
</div>
</div>
</div>
</section>
</div>
</main><!-- End #main -->
<script>
const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#password');
togglePassword.addEventListener('click', function (e) {
// toggle the type attribute
const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
// toggle the eye slash icon
if(type == "password"){
this.classList.remove('bi-eye-slash');
this.classList.add('bi-eye');
} else if(type == "text"){
this.classList.remove('bi-eye');
this.classList.add('bi-eye-slash');
}
password.setAttribute('type', type);
});
const togglePassword2 = document.querySelector('#togglePassword2');
const password2 = document.querySelector('#password2');
togglePassword2.addEventListener('click', function (e) {
// toggle the type attribute
const type = password2.getAttribute('type') === 'password' ? 'text' : 'password';
// toggle the eye slash icon
if(type == "password"){
this.classList.remove('bi-eye-slash');
this.classList.add('bi-eye');
} else if(type == "text"){
this.classList.remove('bi-eye');
this.classList.add('bi-eye-slash');
}
password2.setAttribute('type', type);
});
</script>{% endblock body %}

View File

@ -1,68 +0,0 @@
{% extends "ereuse_devicehub/base.html" %}
{% block page_title %}Login{% endblock %}
{% block body %}
<main>
<div class="container">
<section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center">
<div class="d-flex justify-content-center py-4">
<a href="{{ url_for('core.login') }}" class="d-flex align-items-center w-auto">
<img src="{{ url_for('static', filename='img/usody_logo_transparent_noicon-y-purple-120x41.png') }}" alt="">
</a>
</div><!-- End Logo -->
<div class="card mb-3">
<div class="card-body">
{% if is_valid %}
<div class="pt-4 pb-2">
<h5 class="card-title text-center pb-0 fs-4">User is valid</h5>
<div class="col-12 text-center">
You have successfully activated your account!<br />
<a style="color: #cc0066;" href="{{ url_for('core.login') }}">Sign in</a>.
</div>
</div>
{% else %}
<div class="pt-4 pb-2">
<h5 class="card-title text-center pb-0 fs-4">User is Invalid</h5>
<div class="row">
<div class="col-12 text-center">
<span class="text-danger">Invalid</span>
</div>
</div>
<div class="row">
<div class="col-12">
Sorry, your token not exist or is expired.
</div>
</div>
</div>
{% endif %}
</div>
</div>
<div class="credits">
<a href="https://help.usody.com/en/getting-started/introduction/" target="_blank">Help</a> |
<a href="https://pangea.org/es/politica-de-privacidad/" target="_blank">Privacy</a> |
<a href="https://pangea.org/aviso-legal/" target="_blank">Terms</a>
</div>
</div>
</div>
</div>
</section>
</div>
</main><!-- End #main -->
{% endblock body %}

View File

@ -1,50 +0,0 @@
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

@ -119,19 +119,3 @@ class Session(Thing):
def __str__(self) -> str: def __str__(self) -> str:
return '{0.token}'.format(self) return '{0.token}'.format(self)
class UserValidation(Thing):
id = Column(BigInteger, Sequence('user_validation_seq'), primary_key=True)
expired = Column(BigInteger, default=0)
joined_at = db.Column(db.DateTime())
token = Column(UUID(as_uuid=True), default=uuid4, unique=True, nullable=False)
user_id = db.Column(db.UUID(as_uuid=True), db.ForeignKey(User.id))
user = db.relationship(
User,
backref=db.backref('user_validation', lazy=True, collection_class=set),
collection_class=set,
)
def __str__(self) -> str:
return '{0.token}'.format(self)

View File

@ -22,7 +22,6 @@ from ereuse_devicehub.devicehub import Devicehub
from ereuse_devicehub.inventory.views import devices from ereuse_devicehub.inventory.views import devices
from ereuse_devicehub.labels.views import labels from ereuse_devicehub.labels.views import labels
from ereuse_devicehub.mail.flask_mail import Mail from ereuse_devicehub.mail.flask_mail import Mail
from ereuse_devicehub.register.views import register
from ereuse_devicehub.resources.agent.models import Person from ereuse_devicehub.resources.agent.models import Person
from ereuse_devicehub.resources.enums import SessionType from ereuse_devicehub.resources.enums import SessionType
from ereuse_devicehub.resources.tag import Tag from ereuse_devicehub.resources.tag import Tag
@ -66,7 +65,6 @@ def _app(config: TestConfig) -> Devicehub:
app.register_blueprint(labels) app.register_blueprint(labels)
app.register_blueprint(api) app.register_blueprint(api)
app.register_blueprint(workbench) app.register_blueprint(workbench)
app.register_blueprint(register)
app.config["SQLALCHEMY_RECORD_QUERIES"] = True app.config["SQLALCHEMY_RECORD_QUERIES"] = True
app.config['PROFILE'] = True app.config['PROFILE'] = True
# app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) # app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])

View File

@ -106,8 +106,6 @@ def test_api_docs(client: Client):
'/versions/', '/versions/',
'/workbench/', '/workbench/',
'/workbench/erasure_host/{id}/', '/workbench/erasure_host/{id}/',
'/new_register/',
'/validate_user/{token}',
} }
assert docs['info'] == {'title': 'Devicehub', 'version': '0.2'} assert docs['info'] == {'title': 'Devicehub', 'version': '0.2'}
assert docs['components']['securitySchemes']['bearerAuth'] == { assert docs['components']['securitySchemes']['bearerAuth'] == {

View File

@ -16,7 +16,7 @@ from ereuse_devicehub.parser.models import SnapshotsLog
from ereuse_devicehub.resources.action.models import Snapshot from ereuse_devicehub.resources.action.models import Snapshot
from ereuse_devicehub.resources.device.models import Device, Placeholder from ereuse_devicehub.resources.device.models import Device, Placeholder
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 tests import conftest from tests import conftest
@ -2604,34 +2604,6 @@ def test_snapshot_is_server_erase(user3: UserClientFlask):
assert snapshot2 in snapshot.device.actions assert snapshot2 in snapshot.device.actions
@pytest.mark.mvp
@pytest.mark.usefixtures(conftest.app_context.__name__)
def test_new_register(user3: UserClientFlask, app: Devicehub):
uri = '/new_register/'
body, status = user3.get(uri)
assert "Create your account" in body
data = {
'csrf_token': generate_csrf(),
'email': "foo@bar.cxm",
'password': "123456",
'password2': "123456",
'name': "booBar",
}
body, status = user3.post(uri, data=data)
assert status == '200 OK'
assert "Please check your email." in body
user_valid = UserValidation.query.one()
assert user_valid.user.active is False
uri = '/validate_user/' + str(user_valid.token)
body, status = user3.get(uri)
assert status == '200 OK'
assert "You have successfully activated your account!" in body
assert user_valid.user.active
@pytest.mark.mvp @pytest.mark.mvp
@pytest.mark.usefixtures(conftest.app_context.__name__) @pytest.mark.usefixtures(conftest.app_context.__name__)
def test_system_uuid_motherboard(user3: UserClientFlask): def test_system_uuid_motherboard(user3: UserClientFlask):