"""Kanban sign-in and sign-out.""" import hashlib import secrets from fastapi import APIRouter, HTTPException, Request, Response from ...core import db from ...core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, login_failed, password_matches, throttle) from ...core.models import OperatorLogin router = APIRouter() @router.post('/api/operator/login') def operator_login(body: OperatorLogin, request: Request, response: Response): email = body.email throttle('operator:'+email, request) with db.connect() as c: account = c.execute('SELECT * FROM dtf_local.operators WHERE email=%s', (email,)).fetchone() if not c.execute('SELECT 1 FROM dtf_local.operators WHERE active LIMIT 1').fetchone(): raise HTTPException(503, 'Nenhuma conta de operador configurada.') # Comparable password work whether or not the account exists or is active. stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH matches = password_matches(body.password, stored) if not account or not account['active'] or not matches: login_failed('operator:'+email) audit('operator_login_failed', ip=client_ip(request), operator=email) raise HTTPException(401, 'E-mail ou senha inválidos.') token = secrets.token_urlsafe(32) with db.connect() as c: previous = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest() c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (previous,)) c.execute('INSERT INTO dtf_local.operator_sessions(token_hash,username) VALUES(%s,%s)', (hashlib.sha256(token.encode()).hexdigest(), email)) c.execute('UPDATE dtf_local.operators SET last_login_at=now() WHERE id=%s', (account['id'],)) response.set_cookie('dtf_operator', token, httponly=True, secure=COOKIE_SECURE, samesite='strict', path='/api/operator', max_age=28800) audit('operator_login_success', operator=email) return {'ok': True} @router.post('/api/operator/logout') def operator_logout(request: Request, response: Response): with db.connect() as c: digest = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest() c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (digest,)) response.delete_cookie('dtf_operator', path='/api/operator', httponly=True, secure=COOKIE_SECURE, samesite='strict') audit('operator_logout') return {'ok': True}