Files
dtf-system/app/api/users.py
Cauê Faleiros 3664fe827e feat: password recovery by e-mail, team alerts, and a price for files opened by hand
Pilot customers had no way to reset a forgotten password, and the 7 October
meeting asked for two things that only needed the client's inputs to go live.

Password recovery: "Esqueci minha senha" in Minha conta sends a link that
works once, for an hour (/conta/redefinir#token, in the fragment so it never
reaches a server or a Referer). Only the token's hash is stored, the e-mail's
text is erased once sent, the answer never says whether an account exists,
and a reset signs out every other session. Limited per address and source.

Team alerts: Kanban users who tick "Receber alertas por e-mail" in Usuários
get one when an order is paid, a cart waits for review, or a payment needs
attention. Messages are queued in the transaction that caused them and sent
by the worker with retries (app/mail.py). Integrações shows an E-mail row
with "Enviar teste".

E-mail is off in production (MAIL_ADAPTER=off; recovery keeps offering
WhatsApp) until the client's SMTP account exists; then it is only settings
(docs/PORTAINER.md). The local stack keeps messages in the database and log.

Files opened by hand: a finished sheet in CDR, AI, PSD or TIFF (or with a
length the customer typed) pays the full price plus MANUAL_FILE_EXTRA_CENTS
per metre, to steer customers to PNG as the meeting asked. It is 0 until
Marcus gives the amount. The Site shows it before checkout, the server
charges it, Tiny gets it in the unit price, and the Kanban says it.

Tested: new tests/mail_test (reset flow, SMTP delivery against a local SMTP
server, retry, who gets alerts), pricing unit tests, and the browser test now
checks the Site total equals the server's, run with the charge at 0 and at
R$ 5,00. The full CI suite passes in a CI-style stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:48:24 -03:00

227 lines
11 KiB
Python

"""Kanban users and print machines, managed by the administrators.
An administrator creates each account with a first password and the person
changes it in "Minha senha". Whoever wants the team's alerts by e-mail has
them switched on here. The superadmin is
the system's own account, set from the console (python -m app.operators);
administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident.
"""
import re
from typing import Literal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, field_validator
from .. import mail
from ..core import db
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
from ..core.models import StrictModel
router = APIRouter()
class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80)
email: str = Field(min_length=3, max_length=254)
role: Literal['admin', 'gestao', 'operador', 'vendedor']
password: str | None = Field(default=None, min_length=12, max_length=128)
active: bool = True
machines: list[UUID] = Field(default_factory=list, max_length=50)
# The team's alerts by e-mail: orders paid, carts waiting for review, payments to look at.
alerts: bool = False
@field_validator('email')
@classmethod
def email_valid(cls, value):
value = value.strip().lower()
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
raise ValueError('Informe um e-mail válido.')
return value
class MachineIn(StrictModel):
name: str = Field(min_length=1, max_length=60)
products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2)
active: bool = True
class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=12, max_length=128)
@router.get('/api/operator/me')
def me(request: Request):
"""Who is signed in, and what the Kanban should offer them."""
account = signed_in(request)
return {'email': account['email'], 'name': account['name'], 'role': account['role'],
'machines': account['machines'],
'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)}
@router.post('/api/operator/me/password')
def change_password(body: PasswordChange, request: Request):
account = signed_in(request)
with db.connect() as c:
row = c.execute('SELECT password_hash FROM dtf_local.operators WHERE id=%s', (account['id'],)).fetchone()
if not password_matches(body.current, row['password_hash']):
raise HTTPException(403, 'A senha atual não confere.')
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.new), account['id']))
audit('operator_password_changed', operator=account['email'])
return {'ok': True}
def user_rows(c):
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.alerts,o.last_login_at,o.created_at,
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
for row in rows:
row['machines'] = [str(m) for m in row['machines']]
return rows
@router.get('/api/operator/users')
def list_users(user=Depends(can('users'))):
with db.connect() as c:
return {'users': user_rows(c), 'machines': machine_rows(c)}
def target(c, uid, request):
"""The account to change, refusing a superadmin unless one is asking."""
row = c.execute('SELECT * FROM dtf_local.operators WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Usuário não encontrado.')
if row['role'] == 'superadmin' and request.state.operator['role'] != 'superadmin':
raise HTTPException(403, 'Só o superadmin altera esta conta.')
return row
def set_machines(c, uid, machines):
known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)',
([str(m) for m in machines],)).fetchall()}
if len(known) != len(set(map(str, machines))):
raise HTTPException(422, 'Uma das máquinas escolhidas não existe mais.')
c.execute('DELETE FROM dtf_local.operator_machines WHERE operator_id=%s', (uid,))
for machine in known:
c.execute('INSERT INTO dtf_local.operator_machines(operator_id,machine_id) VALUES(%s,%s)', (uid, machine))
@router.post('/api/operator/users')
def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
if not body.password:
raise HTTPException(422, 'Defina uma senha inicial com 12 caracteres ou mais.')
uid = uuid4()
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active,alerts)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active, body.alerts))
set_machines(c, uid, body.machines)
audit('operator_created', operator=user, account=body.email, role=body.role)
return {'id': str(uid)}
@router.post('/api/operator/users/{uid}')
def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('users'))):
me_ = request.state.operator
with db.connect() as c:
row = target(c, uid, request)
# A superadmin keeps that profile: the form offers only the assignable ones.
role = row['role'] if row['role'] == 'superadmin' else body.role
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role']):
raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.')
if body.email != row['email'] and c.execute(
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s,alerts=%s WHERE id=%s',
(body.name.strip(), body.email, role, body.active, body.alerts, uid))
if body.password:
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
if body.email != row['email']:
c.execute('UPDATE dtf_local.operator_sessions SET username=%s WHERE username=%s', (body.email, row['email']))
if not body.active or body.password:
# Disabled, or given a new password: whoever was signed in signs in again.
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
set_machines(c, uid, body.machines)
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
password_reset=bool(body.password))
return {'ok': True}
@router.post('/api/operator/users/{uid}/delete')
def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
with db.connect() as c:
row = target(c, uid, request)
if str(row['id']) == str(request.state.operator['id']):
raise HTTPException(409, 'Você não pode excluir a sua própria conta.')
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (row['email'],))
c.execute('DELETE FROM dtf_local.operators WHERE id=%s', (uid,))
# The movement history keeps the e-mail of whoever moved each card.
audit('operator_deleted', operator=user, account=row['email'])
return {'ok': True}
def machine_rows(c):
rows = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY active DESC, name').fetchall()
for row in rows:
row['id'] = str(row['id'])
return rows
@router.get('/api/operator/machines')
def list_machines(user=Depends(can('view'))):
with db.connect() as c:
return {'machines': machine_rows(c)}
@router.post('/api/operator/machines')
def create_machine(body: MachineIn, user=Depends(can('users'))):
mid = uuid4()
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('INSERT INTO dtf_local.machines(id,name,products,active) VALUES(%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active))
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@router.post('/api/operator/machines/{mid}')
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
(body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
if not c.execute('UPDATE dtf_local.machines SET name=%s,products=%s,active=%s WHERE id=%s RETURNING id',
(body.name.strip(), sorted(set(body.products)), body.active, mid)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
audit('machine_updated', operator=user, machine=body.name)
return {'ok': True}
@router.post('/api/operator/machines/{mid}/delete')
def delete_machine(mid: UUID, user=Depends(can('users'))):
"""Its orders go back to the automatic choice; its operators lose it."""
with db.connect() as c:
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True}
@router.post('/api/operator/mail/test')
def test_mail(request: Request, user=Depends(can('manage'))):
"""A message to whoever asked, to prove the mail server works."""
with db.connect() as c:
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
'recuperação de senha dos clientes e alertas da equipe.'):
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
audit('mail_test_queued', operator=user)
return {'ok': True, 'to': user}