Merge pull request #386 from eReuse/feature/3729-user-registration

Feature/3729 user registration
This commit is contained in:
cayop 2022-10-20 18:03:09 +02:00 committed by GitHub
commit 13605abbaf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 1124 additions and 13 deletions

View File

@ -86,3 +86,10 @@ class DevicehubConfig(Config):
"""Definition of path where save the documents of customers"""
PATH_DOCUMENTS_STORAGE = config('PATH_DOCUMENTS_STORAGE', '/tmp/')
JWT_PASS = config('JWT_PASS', '')
MAIL_SERVER = config('MAIL_SERVER', '')
MAIL_USERNAME = config('MAIL_USERNAME', '')
MAIL_PASSWORD = config('MAIL_PASSWORD', '')
MAIL_PORT = config('MAIL_PORT', 587)
MAIL_USE_TLS = config('MAIL_USE_TLS', True)
MAIL_DEFAULT_SENDER = config('MAIL_DEFAULT_SENDER', '')

View File

@ -1,10 +1,20 @@
from flask import g
from flask import current_app as app
from flask import g, render_template
from flask_wtf import FlaskForm
from werkzeug.security import generate_password_hash
from wtforms import BooleanField, EmailField, PasswordField, validators
from wtforms import (
BooleanField,
EmailField,
PasswordField,
StringField,
TelField,
validators,
)
from ereuse_devicehub.db import db
from ereuse_devicehub.resources.user.models import User
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 LoginForm(FlaskForm):
@ -101,3 +111,100 @@ class PasswordForm(FlaskForm):
if commit:
db.session.commit()
return
class UserNewRegisterForm(FlaskForm):
email = EmailField(
'Email Address', [validators.DataRequired(), validators.Length(min=6, max=35)]
)
password = PasswordField('Password', [validators.DataRequired()])
password2 = PasswordField('Password', [validators.DataRequired()])
name = StringField(
'Name', [validators.DataRequired(), validators.Length(min=3, max=35)]
)
telephone = TelField(
'Telephone', [validators.DataRequired(), validators.Length(min=9, 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, telephone=self.telephone.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'
message = render_template(template, url=url)
subject = "Validate email for register in Usody.com"
send_email(subject, [self.email.data], message)
def send_mail_admin(self, user):
person = next(iter(user.individuals))
context = {
'email': person.email,
'name': person.name,
'telephone': person.telephone,
}
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

@ -187,10 +187,6 @@ class FilterForm(FlaskForm):
if filter_type:
self.devices = self.devices.filter(Device.type.in_(filter_type))
# if self.device_type in STORAGE + ["All DataStorage"]:
# import pdb; pdb.set_trace()
# self.devices = self.devices.filter(Component.parent_id.is_(None))
return self.devices.order_by(Device.updated.desc())

View File

View File

@ -0,0 +1,622 @@
# -*- coding: utf-8 -*-
"""
flaskext.mail
~~~~~~~~~~~~~
Flask extension for sending email.
:copyright: (c) 2010 by Dan Jacob.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
__version__ = '0.9.1'
import re
import smtplib
import sys
import time
import unicodedata
from contextlib import contextmanager
from email import charset
from email.encoders import encode_base64
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr, formatdate, make_msgid, parseaddr
import blinker
from flask import current_app
PY3 = sys.version_info[0] == 3
PY34 = PY3 and sys.version_info[1] >= 4
basestring = str
unicode = str
if PY3:
string_types = (str,)
text_type = str
from email import policy
message_policy = policy.SMTP
else:
string_types = (basestring,)
text_type = unicode
message_policy = None
charset.add_charset('utf-8', charset.SHORTEST, None, 'utf-8')
class FlaskMailUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args)
def __str__(self):
original = UnicodeDecodeError.__str__(self)
return '%s. You passed in %r (%s)' % (original, self.obj, type(self.obj))
def force_text(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
strings_only = True
if isinstance(s, text_type):
return s
try:
if not isinstance(s, string_types):
if PY3:
if isinstance(s, bytes):
s = text_type(s, encoding, errors)
else:
s = text_type(s)
elif hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
s = text_type(bytes(s), encoding, errors)
else:
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise FlaskMailUnicodeDecodeError(s, *e.args)
else:
s = ' '.join([force_text(arg, encoding, strings_only, errors) for arg in s])
return s
def sanitize_subject(subject, encoding='utf-8'):
try:
subject.encode('ascii')
except UnicodeEncodeError:
try:
subject = Header(subject, encoding).encode()
except UnicodeEncodeError:
subject = Header(subject, 'utf-8').encode()
return subject
def sanitize_address(addr, encoding='utf-8'):
if isinstance(addr, string_types):
addr = parseaddr(force_text(addr))
nm, addr = addr
try:
nm = Header(nm, encoding).encode()
except UnicodeEncodeError:
nm = Header(nm, 'utf-8').encode()
try:
addr.encode('ascii')
except UnicodeEncodeError: # IDN
if '@' in addr:
localpart, domain = addr.split('@', 1)
localpart = str(Header(localpart, encoding))
domain = domain.encode('idna').decode('ascii')
addr = '@'.join([localpart, domain])
else:
addr = Header(addr, encoding).encode()
return formataddr((nm, addr))
def sanitize_addresses(addresses, encoding='utf-8'):
return map(lambda e: sanitize_address(e, encoding), addresses)
def _has_newline(line):
"""Used by has_bad_header to check for \\r or \\n"""
if line and ('\r' in line or '\n' in line):
return True
return False
class Connection(object):
"""Handles connection to host."""
def __init__(self, mail):
self.mail = mail
def __enter__(self):
if self.mail.suppress:
self.host = None
else:
self.host = self.configure_host()
self.num_emails = 0
return self
def __exit__(self, exc_type, exc_value, tb):
if self.host:
self.host.quit()
def configure_host(self):
if self.mail.use_ssl:
host = smtplib.SMTP_SSL(self.mail.server, self.mail.port)
else:
host = smtplib.SMTP(self.mail.server, self.mail.port)
host.set_debuglevel(int(self.mail.debug))
if self.mail.use_tls:
host.starttls()
if self.mail.username and self.mail.password:
host.login(self.mail.username, self.mail.password)
return host
def send(self, message, envelope_from=None):
"""Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command.
"""
assert message.send_to, "No recipients have been added"
assert message.sender, (
"The message does not specify a sender and a default sender "
"has not been configured"
)
if message.has_bad_headers():
raise BadHeaderError
if message.date is None:
message.date = time.time()
if self.host:
self.host.sendmail(
sanitize_address(envelope_from or message.sender),
list(sanitize_addresses(message.send_to)),
message.as_bytes() if PY3 else message.as_string(),
message.mail_options,
message.rcpt_options,
)
email_dispatched.send(message, app=current_app._get_current_object())
self.num_emails += 1
if self.num_emails == self.mail.max_emails:
self.num_emails = 0
if self.host:
self.host.quit()
self.host = self.configure_host()
def send_message(self, *args, **kwargs):
"""Shortcut for send(msg).
Takes same arguments as Message constructor.
:versionadded: 0.3.5
"""
self.send(Message(*args, **kwargs))
class BadHeaderError(Exception):
pass
class Attachment(object):
"""Encapsulates file attachment information.
:versionadded: 0.3.5
:param filename: filename of attachment
:param content_type: file mimetype
:param data: the raw file data
:param disposition: content-disposition (if any)
"""
def __init__(
self,
filename=None,
content_type=None,
data=None,
disposition=None,
headers=None,
):
self.filename = filename
self.content_type = content_type
self.data = data
self.disposition = disposition or 'attachment'
self.headers = headers or {}
class Message(object):
"""Encapsulates an email message.
:param subject: email subject header
:param recipients: list of email addresses
:param body: plain text message
:param html: HTML message
:param sender: email sender address, or **MAIL_DEFAULT_SENDER** by default
:param cc: CC list
:param bcc: BCC list
:param attachments: list of Attachment instances
:param reply_to: reply-to address
:param date: send date
:param charset: message character set
:param extra_headers: A dictionary of additional headers for the message
:param mail_options: A list of ESMTP options to be used in MAIL FROM command
:param rcpt_options: A list of ESMTP options to be used in RCPT commands
"""
def __init__(
self,
subject='',
recipients=None,
body=None,
html=None,
sender=None,
cc=None,
bcc=None,
attachments=None,
reply_to=None,
date=None,
charset=None,
extra_headers=None,
mail_options=None,
rcpt_options=None,
):
sender = sender or current_app.extensions['mail'].default_sender
if isinstance(sender, tuple):
sender = "%s <%s>" % sender
self.recipients = recipients or []
self.subject = subject
self.sender = sender
self.reply_to = reply_to
self.cc = cc or []
self.bcc = bcc or []
self.body = body
self.html = html
self.date = date
self.msgId = make_msgid()
self.charset = charset
self.extra_headers = extra_headers
self.mail_options = mail_options or []
self.rcpt_options = rcpt_options or []
self.attachments = attachments or []
@property
def send_to(self):
return set(self.recipients) | set(self.bcc or ()) | set(self.cc or ())
def _mimetext(self, text, subtype='plain'):
"""Creates a MIMEText object with the given subtype (default: 'plain')
If the text is unicode, the utf-8 charset is used.
"""
charset = self.charset or 'utf-8'
return MIMEText(text, _subtype=subtype, _charset=charset)
def _message(self): # noqa: C901
"""Creates the email"""
ascii_attachments = current_app.extensions['mail'].ascii_attachments
encoding = self.charset or 'utf-8'
attachments = self.attachments or []
if len(attachments) == 0 and not self.html:
# No html content and zero attachments means plain text
msg = self._mimetext(self.body)
elif len(attachments) > 0 and not self.html:
# No html and at least one attachment means multipart
msg = MIMEMultipart()
msg.attach(self._mimetext(self.body))
else:
# Anything else
msg = MIMEMultipart()
alternative = MIMEMultipart('alternative')
alternative.attach(self._mimetext(self.body, 'plain'))
alternative.attach(self._mimetext(self.html, 'html'))
msg.attach(alternative)
if self.subject:
msg['Subject'] = sanitize_subject(force_text(self.subject), encoding)
msg['From'] = sanitize_address(self.sender, encoding)
msg['To'] = ', '.join(list(set(sanitize_addresses(self.recipients, encoding))))
msg['Date'] = formatdate(self.date, localtime=True)
# see RFC 5322 section 3.6.4.
msg['Message-ID'] = self.msgId
if self.cc:
msg['Cc'] = ', '.join(list(set(sanitize_addresses(self.cc, encoding))))
if self.reply_to:
msg['Reply-To'] = sanitize_address(self.reply_to, encoding)
if self.extra_headers:
for k, v in self.extra_headers.items():
msg[k] = v
SPACES = re.compile(r'[\s]+', re.UNICODE)
for attachment in attachments:
f = MIMEBase(*attachment.content_type.split('/'))
f.set_payload(attachment.data)
encode_base64(f)
filename = attachment.filename
if filename and ascii_attachments:
# force filename to ascii
filename = unicodedata.normalize('NFKD', filename)
filename = filename.encode('ascii', 'ignore').decode('ascii')
filename = SPACES.sub(u' ', filename).strip()
try:
filename and filename.encode('ascii')
except UnicodeEncodeError:
if not PY3:
filename = filename.encode('utf8')
filename = ('UTF8', '', filename)
f.add_header(
'Content-Disposition', attachment.disposition, filename=filename
)
for key, value in attachment.headers:
f.add_header(key, value)
msg.attach(f)
if message_policy:
msg.policy = message_policy
return msg
def as_string(self):
return self._message().as_string()
def as_bytes(self):
# if PY34:
# return self._message().as_bytes()
# else: # fallback for old Python (3) versions
# return self._message().as_string().encode(self.charset or 'utf-8')
return self._message().as_string().encode(self.charset or 'utf-8')
def __str__(self):
return self.as_string()
def __bytes__(self):
return self.as_bytes()
def has_bad_headers(self):
"""Checks for bad headers i.e. newlines in subject, sender or recipients.
RFC5322: Allows multiline CRLF with trailing whitespace (FWS) in headers
"""
headers = [self.sender, self.reply_to] + self.recipients
for header in headers:
if _has_newline(header):
return True
if self.subject:
if _has_newline(self.subject):
for linenum, line in enumerate(self.subject.split('\r\n')):
if not line:
return True
if linenum > 0 and line[0] not in '\t ':
return True
if _has_newline(line):
return True
if len(line.strip()) == 0:
return True
return False
def is_bad_headers(self):
from warnings import warn
msg = (
'is_bad_headers is deprecated, use the new has_bad_headers method instead.'
)
warn(DeprecationWarning(msg), stacklevel=1)
return self.has_bad_headers()
def send(self, connection):
"""Verifies and sends the message."""
connection.send(self)
def add_recipient(self, recipient):
"""Adds another recipient to the message.
:param recipient: email address of recipient.
"""
self.recipients.append(recipient)
def attach(
self,
filename=None,
content_type=None,
data=None,
disposition=None,
headers=None,
):
"""Adds an attachment to the message.
:param filename: filename of attachment
:param content_type: file mimetype
:param data: the raw file data
:param disposition: content-disposition (if any)
"""
self.attachments.append(
Attachment(filename, content_type, data, disposition, headers)
)
class _MailMixin(object):
@contextmanager
def record_messages(self):
"""Records all messages. Use in unit tests for example::
with mail.record_messages() as outbox:
response = app.test_client.get("/email-sending-view/")
assert len(outbox) == 1
assert outbox[0].subject == "testing"
You must have blinker installed in order to use this feature.
:versionadded: 0.4
"""
if not email_dispatched:
raise RuntimeError("blinker must be installed")
outbox = []
def _record(message, app):
outbox.append(message)
email_dispatched.connect(_record)
try:
yield outbox
finally:
email_dispatched.disconnect(_record)
def send(self, message):
"""Sends a single message instance. If TESTING is True the message will
not actually be sent.
:param message: a Message instance.
"""
with self.connect() as connection:
message.send(connection)
def send_message(self, *args, **kwargs):
"""Shortcut for send(msg).
Takes same arguments as Message constructor.
:versionadded: 0.3.5
"""
self.send(Message(*args, **kwargs))
def connect(self):
"""Opens a connection to the mail host."""
app = getattr(self, "app", None) or current_app
try:
return Connection(app.extensions['mail'])
except KeyError:
raise RuntimeError(
"The curent application was not configured with Flask-Mail"
)
class _Mail(_MailMixin):
def __init__(
self,
server,
username,
password,
port,
use_tls,
use_ssl,
default_sender,
debug,
max_emails,
suppress,
ascii_attachments=False,
):
self.server = server
self.username = username
self.password = password
self.port = port
self.use_tls = use_tls
self.use_ssl = use_ssl
self.default_sender = default_sender
self.debug = debug
self.max_emails = max_emails
self.suppress = suppress
self.ascii_attachments = ascii_attachments
class Mail(_MailMixin):
"""Manages email messaging
:param app: Flask instance
"""
def __init__(self, app=None):
self.app = app
if app is not None:
self.state = self.init_app(app)
else:
self.state = None
def init_mail(self, config, debug=False, testing=False):
return _Mail(
config.get('MAIL_SERVER', '127.0.0.1'),
config.get('MAIL_USERNAME'),
config.get('MAIL_PASSWORD'),
config.get('MAIL_PORT', 25),
config.get('MAIL_USE_TLS', False),
config.get('MAIL_USE_SSL', False),
config.get('MAIL_DEFAULT_SENDER'),
int(config.get('MAIL_DEBUG', debug)),
config.get('MAIL_MAX_EMAILS'),
config.get('MAIL_SUPPRESS_SEND', testing),
config.get('MAIL_ASCII_ATTACHMENTS', False),
)
def init_app(self, app):
"""Initializes your mail settings from the application settings.
You can use this if you want to set up your Mail instance
at configuration time.
:param app: Flask application instance
"""
state = self.init_mail(app.config, app.debug, app.testing)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['mail'] = state
return state
def __getattr__(self, name):
return getattr(self.state, name, None)
signals = blinker.Namespace()
email_dispatched = signals.signal(
"email-dispatched",
doc="""
Signal sent when an email is dispatched. This signal will also be sent
in testing mode, even though the email will not actually be sent.
""",
)

View File

@ -0,0 +1,31 @@
import logging
from smtplib import SMTPException
from threading import Thread
from flask import current_app as app
from ereuse_devicehub.mail.flask_mail import Message
logger = logging.getLogger(__name__)
def _send_async_email(app, msg):
with app.app_context():
try:
app.mail.send(msg)
except SMTPException:
logger.exception("An error occurred while sending the email")
def send_email(
subject, recipients, text_body, sender=None, cc=None, bcc=None, html_body=None
):
msg = Message(subject, sender=sender, recipients=recipients, cc=cc, bcc=bcc)
msg.body = text_body
if html_body:
msg.html = html_body
Thread(target=_send_async_email, args=(app._get_current_object(), msg)).start()

View File

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

@ -119,3 +119,19 @@ class Session(Thing):
def __str__(self) -> str:
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

@ -0,0 +1,4 @@
A new user has been registered. These are your data
Name: {{ name }}
Telephone: {{ telephone }}
Email: {{ email }}

View File

@ -0,0 +1,2 @@
Hello, you are register in Usody.com
Please for activate your account click in the next address: {{ url }}

View File

@ -60,7 +60,7 @@
<button class="btn btn-primary w-100" type="submit">Login</button>
</div>
<div class="col-12">
<p class="small mb-0">Don't have account? <a href="#TODO" onclick="$('#exampleModal').modal('show')" data-toggle="modal" data-target="#exampleModal">Create an account</a></p>
<p class="small mb-0">Don't have account? <a href="{{ url_for('core.user-registration') }}">Create an account</a></p>
</div>
</form>

View File

@ -0,0 +1,121 @@
{% 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="logo d-flex align-items-center w-auto">
<img src="{{ url_for('static', filename='img/logo_usody_clock.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">Register as a new User</h5>
{% if not form._token %}
<p class="text-center small">Enter an Email & password for to do a new register.</p>
{% 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">
<label for="yourEmail" class="form-label">Email</label>
<input type="email" name="email" class="form-control" id="yourEmail" 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">
<label for="password" class="form-label">Password</label>
<input type="password" name="password" class="form-control" id="password" required>
<div class="invalid-feedback">Please enter a password!</div>
</div>
<div class="col-12">
<label for="password2" class="form-label">Password</label>
<input type="password" name="password2" class="form-control" id="password2" required>
<div class="invalid-feedback">Please enter a password again!</div>
</div>
<div class="col-12">
<label for="name" class="form-label">Name</label>
<input name="name" class="form-control" 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">
<label for="telephone" class="form-label">Telephone</label>
<input type="tel" name="telephone" class="form-control" id="telephone" required>
{% if form.telephone.errors %}
<p class="text-danger">
{% for error in form.telephone.errors %}
{{ error }}<br/>
{% endfor %}
</p>
{% endif %}
</div>
<div class="col-12">
<button class="btn btn-primary w-100" type="submit">Register</button>
</div>
<div class="col-12">
<p class="small mb-0">
You have account? <a href="{{ url_for('core.login') }}">do Login</a>
</p>
</div>
</form>
{% else %}
</div>
<div class="col-12 p-4">
We have sent you a validation email.<br />
Please check your email.
</div>
{% endif %}
</div>
</div>
<div class="credits">
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
</div>
</div>
</section>
</div>
</main><!-- End #main -->
{% endblock body %}

View File

@ -0,0 +1,66 @@
{% 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="logo d-flex align-items-center w-auto">
<img src="{{ url_for('static', filename='img/logo_usody_clock.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">
Your new user is activate.</br />
Now you can do <a style="color: #cc0066;" href="{{ url_for('core.login') }}">Login</a> and entry.
</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">
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
</div>
</div>
</section>
</div>
</main><!-- End #main -->
{% endblock body %}

View File

@ -6,10 +6,10 @@ from sqlalchemy import or_
from ereuse_devicehub import __version__, messages
from ereuse_devicehub.db import db
from ereuse_devicehub.forms import LoginForm, PasswordForm
from ereuse_devicehub.forms import LoginForm, PasswordForm, UserNewRegisterForm
from ereuse_devicehub.resources.action.models import Trade
from ereuse_devicehub.resources.lot.models import Lot
from ereuse_devicehub.resources.user.models import User
from ereuse_devicehub.resources.user.models import User, UserValidation
from ereuse_devicehub.utils import is_safe_url
core = Blueprint('core', __name__)
@ -108,7 +108,44 @@ class UserPasswordView(View):
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('/logout/', view_func=LogoutView.as_view('logout'))
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'))

View File

@ -11,6 +11,7 @@ from ereuse_devicehub.config import DevicehubConfig
from ereuse_devicehub.devicehub import Devicehub
from ereuse_devicehub.inventory.views import devices
from ereuse_devicehub.labels.views import labels
from ereuse_devicehub.mail.flask_mail import Mail
from ereuse_devicehub.views import core
from ereuse_devicehub.workbench.views import workbench
@ -44,6 +45,9 @@ app.register_blueprint(labels)
app.register_blueprint(api)
app.register_blueprint(workbench)
mail = Mail(app)
app.mail = mail
# configure & enable CSRF of Flask-WTF
# NOTE: enable by blueprint to exclude API views
# TODO(@slamora: enable by default & exclude API views when decouple of Teal is completed

View File

@ -39,3 +39,6 @@ et_xmlfile==1.1.0 # pandas dependency
# manual dependency
marshmallow-enum==1.4.1
# flask_mail dependency
blinker==1.5

View File

@ -1,8 +1,8 @@
#
# This file is autogenerated by pip-compile with python 3.8
# This file is autogenerated by pip-compile with python 3.9
# To update, run:
#
# pip-compile --output-file=requirements.txt requirements.in
# pip-compile
#
alembic==1.4.2
# via -r requirements.in
@ -12,6 +12,8 @@ apispec==0.39.0
# via teal
atomicwrites==1.4.0
# via -r requirements.in
blinker==1.5
# via -r requirements.in
boltons==18.0.1
# via
# ereuse-utils

View File

@ -21,6 +21,7 @@ from ereuse_devicehub.db import db
from ereuse_devicehub.devicehub import Devicehub
from ereuse_devicehub.inventory.views import devices
from ereuse_devicehub.labels.views import labels
from ereuse_devicehub.mail.flask_mail import Mail
from ereuse_devicehub.resources.agent.models import Person
from ereuse_devicehub.resources.enums import SessionType
from ereuse_devicehub.resources.tag import Tag
@ -46,6 +47,7 @@ class TestConfig(DevicehubConfig):
EMAIL_ADMIN = 'foo@foo.com'
PATH_DOCUMENTS_STORAGE = '/tmp/trade_documents'
JWT_PASS = config('JWT_PASS', '')
MAIL_SUPPRESS_SEND = True
@pytest.fixture(scope='session')
@ -66,6 +68,8 @@ def _app(config: TestConfig) -> Devicehub:
app.config["SQLALCHEMY_RECORD_QUERIES"] = True
app.config['PROFILE'] = True
# app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
mail = Mail(app)
app.mail = mail
return app

View File

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

View File

@ -15,7 +15,7 @@ from ereuse_devicehub.devicehub import Devicehub
from ereuse_devicehub.resources.action.models import Snapshot
from ereuse_devicehub.resources.device.models import Device, Placeholder
from ereuse_devicehub.resources.lot.models import Lot
from ereuse_devicehub.resources.user.models import User
from ereuse_devicehub.resources.user.models import User, UserValidation
from tests import conftest
@ -2578,3 +2578,30 @@ def test_snapshot_is_server_erase(user3: UserClientFlask):
assert snapshot2.is_server_erase
assert snapshot 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/'
user3.get(uri)
data = {
'csrf_token': generate_csrf(),
'email': "foo@bar.cxm",
'password': "1234",
'password2': "1234",
'name': "booBar",
'telephone': "555555555",
}
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 "Your new user is activate" in body
assert user_valid.user.active