feat(auth): implementar soporte de autenticacion en WebApi
This commit is contained in:
+28
-1
@@ -1,10 +1,20 @@
|
||||
from flask import Flask
|
||||
import os
|
||||
|
||||
from flask import Flask, request
|
||||
|
||||
from webapi.blueprints.cacu import cacu_bp
|
||||
from webapi.blueprints.cama import cama_bp
|
||||
from webapi.blueprints.tea import tea_bp
|
||||
|
||||
|
||||
def parse_auth_lite_enabled(value: str | None) -> bool:
|
||||
if value is None or value == "false":
|
||||
return False
|
||||
if value == "true":
|
||||
return True
|
||||
raise ValueError("AUTH_LITE_ENABLED must be exactly 'true' or 'false'")
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
|
||||
@@ -16,4 +26,21 @@ def create_app() -> Flask:
|
||||
app.register_blueprint(cama_bp, url_prefix="/cama")
|
||||
app.register_blueprint(tea_bp, url_prefix="/tea")
|
||||
|
||||
if parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")):
|
||||
from webapi.auth_token import validate_auth_storage
|
||||
from webapi.blueprints.auth import auth_bp
|
||||
|
||||
secret = os.environ.get("AUTH_LITE_SECRET_KEY")
|
||||
if not secret or not secret.strip():
|
||||
raise ValueError("AUTH_LITE_SECRET_KEY is required when Auth-Lite is enabled")
|
||||
validate_auth_storage()
|
||||
app.config["AUTH_LITE_SECRET_KEY"] = secret
|
||||
app.register_blueprint(auth_bp, url_prefix="/auth")
|
||||
|
||||
@app.after_request
|
||||
def auth_no_store(response):
|
||||
if request.path == "/auth" or request.path.startswith("/auth/"):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
return app
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Explicit interactive account bootstrap; never accepts a password argument."""
|
||||
import argparse
|
||||
from getpass import getpass
|
||||
|
||||
from sqlalchemy import delete
|
||||
from sqlmodel import select
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
from core.auth.models import User, UserRole
|
||||
from persistance.db import get_auth_engine, get_auth_session
|
||||
from webapi.auth_token import normalize_username, validate_auth_storage, validate_password
|
||||
|
||||
ALLOWED_ROLES = {"ADMIN", "CACU", "CAMA", "TEA"}
|
||||
|
||||
|
||||
def bootstrap(username: str, roles: list[str], password: str, update: bool = False) -> int:
|
||||
username = normalize_username(username)
|
||||
validate_password(password, minimum=8)
|
||||
if not roles or any(role not in ALLOWED_ROLES for role in roles):
|
||||
raise ValueError("at least one role from ADMIN/CACU/CAMA/TEA is required")
|
||||
validate_auth_storage()
|
||||
with get_auth_session() as session:
|
||||
with session.begin():
|
||||
user = session.exec(select(User).where(User.username == username)).first()
|
||||
if user is not None and not update:
|
||||
raise ValueError("user already exists; use --update explicitly")
|
||||
password_hash = generate_password_hash(password, method="scrypt")
|
||||
if user is None:
|
||||
user = User(username=username, password_hash=password_hash)
|
||||
session.add(user)
|
||||
session.flush()
|
||||
else:
|
||||
user.password_hash = password_hash
|
||||
session.add(user)
|
||||
session.exec(delete(UserRole).where(UserRole.user_id == user.id))
|
||||
for role in sorted(set(roles)):
|
||||
session.add(UserRole(user_id=user.id, role_code=role))
|
||||
user_id = user.id
|
||||
return user_id
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Bootstrap an Auth-Lite account interactively")
|
||||
parser.add_argument("--username", required=True)
|
||||
parser.add_argument("--roles", nargs="+", required=True, choices=sorted(ALLOWED_ROLES))
|
||||
parser.add_argument("--update", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
username = normalize_username(args.username)
|
||||
validate_auth_storage()
|
||||
bootstrap(username, args.roles, getpass("Password: "), update=args.update)
|
||||
print("Auth-Lite account saved.")
|
||||
return 0
|
||||
except ValueError as error:
|
||||
print(str(error))
|
||||
return 1
|
||||
except Exception:
|
||||
print("Auth-Lite bootstrap failed; transaction rolled back.")
|
||||
return 1
|
||||
finally:
|
||||
if get_auth_engine.cache_info().currsize:
|
||||
get_auth_engine().dispose()
|
||||
get_auth_engine.cache_clear()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Explicit, transactional demo account provisioning; never suitable for production."""
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from sqlalchemy import delete
|
||||
from sqlmodel import select
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
from core.auth.models import Role, User, UserRole
|
||||
from persistance.db import get_auth_engine, get_auth_session
|
||||
from webapi import parse_auth_lite_enabled
|
||||
from webapi.auth_bootstrap import ALLOWED_ROLES
|
||||
from webapi.auth_token import normalize_username, validate_auth_storage, validate_password
|
||||
|
||||
# DEMO-ONLY credentials. These credentials are intentionally simple and public
|
||||
# for demonstrations. Do not enable the demo seed in production.
|
||||
DEMO_USERS = (
|
||||
{"username": "admin", "password": "Admin1234", "roles": ("ADMIN",)},
|
||||
{"username": "cacu", "password": "Cacu1234", "roles": ("CACU",)},
|
||||
{"username": "cama", "password": "Cama1234", "roles": ("CAMA",)},
|
||||
{"username": "tea", "password": "Tea12345", "roles": ("TEA",)},
|
||||
)
|
||||
|
||||
|
||||
def validate_demo_users():
|
||||
"""Validate the entire editable definition, including skipped accounts."""
|
||||
validated = []
|
||||
usernames = set()
|
||||
if not DEMO_USERS:
|
||||
raise ValueError("demo configuration must contain accounts")
|
||||
for entry in DEMO_USERS:
|
||||
if not isinstance(entry, dict) or set(entry) != {"username", "password", "roles"}:
|
||||
raise ValueError("invalid demo account definition")
|
||||
username = normalize_username(entry["username"])
|
||||
password = validate_password(entry["password"], minimum=8)
|
||||
roles = entry["roles"]
|
||||
if (not isinstance(roles, (tuple, list)) or not roles
|
||||
or any(not isinstance(role, str) or role not in ALLOWED_ROLES for role in roles)
|
||||
or len(set(roles)) != len(roles)):
|
||||
raise ValueError("demo roles must be unique and from ADMIN/CACU/CAMA/TEA")
|
||||
if username in usernames:
|
||||
raise ValueError("duplicate normalized demo username")
|
||||
usernames.add(username)
|
||||
validated.append({"username": username, "password": password, "roles": tuple(roles)})
|
||||
return validated
|
||||
|
||||
|
||||
def seed_demo_users(*, replace_all: bool = False):
|
||||
"""Complete missing accounts, or replace all, in one transaction.
|
||||
|
||||
The explicit CLI requires Auth enabled. The internal function is also usable
|
||||
with migrated temporary storage in tests; it never creates/migrates storage.
|
||||
"""
|
||||
accounts = validate_demo_users()
|
||||
validate_auth_storage()
|
||||
results = []
|
||||
with get_auth_session() as session:
|
||||
with session.begin():
|
||||
required = {role for account in accounts for role in account["roles"]}
|
||||
if not required <= set(session.exec(select(Role.code))):
|
||||
raise ValueError("required demo roles are missing; apply Auth migration first")
|
||||
existing = set(session.exec(select(User.username)))
|
||||
missing = accounts if replace_all else [a for a in accounts if a["username"] not in existing]
|
||||
# Hash every new password before any delete/insert. No plaintext enters DB.
|
||||
hashes = {a["username"]: generate_password_hash(a["password"], method="scrypt") for a in missing}
|
||||
if replace_all:
|
||||
session.exec(delete(User)) # FK ON DELETE CASCADE clears user_role.
|
||||
for account in accounts:
|
||||
username, roles = account["username"], account["roles"]
|
||||
if username not in hashes:
|
||||
results.append((username, roles, "skipped"))
|
||||
continue
|
||||
user = User(username=username, password_hash=hashes[username])
|
||||
session.add(user)
|
||||
session.flush()
|
||||
for role in roles:
|
||||
session.add(UserRole(user_id=user.id, role_code=role))
|
||||
results.append((username, roles, "created"))
|
||||
return results
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="DEMO ONLY: provision public Auth-Lite accounts")
|
||||
modes = parser.add_mutually_exclusive_group(required=True)
|
||||
modes.add_argument("--ensure", action="store_true", help="create only missing usernames")
|
||||
modes.add_argument("--replace-all", action="store_true", help="delete EVERY Auth user; requires REPLACE")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if not parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")):
|
||||
print("Auth-Lite is disabled; demo seed skipped.")
|
||||
return 0
|
||||
if args.replace_all:
|
||||
print("WARNING: this will delete every Auth-Lite user.")
|
||||
try:
|
||||
confirmation = input("Type REPLACE to continue: ")
|
||||
except EOFError:
|
||||
confirmation = ""
|
||||
if confirmation != "REPLACE":
|
||||
print("Auth-Lite demo replacement cancelled; no changes.")
|
||||
return 0
|
||||
results = seed_demo_users(replace_all=args.replace_all)
|
||||
print("Auth-Lite demo users replaced." if args.replace_all else "Auth-Lite demo seed:")
|
||||
for username, roles, status in results:
|
||||
print(f"{username} [{','.join(roles)}] -> {status}")
|
||||
return 0
|
||||
except Exception:
|
||||
# Editable configuration and DB exceptions may include sensitive values.
|
||||
print("Auth-Lite demo seed failed; transaction rolled back. Check configuration and migrated storage.")
|
||||
return 1
|
||||
finally:
|
||||
if get_auth_engine.cache_info().currsize:
|
||||
get_auth_engine().dispose()
|
||||
get_auth_engine.cache_clear()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Auth-Lite token, input and explicit storage validation helpers."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from itsdangerous import BadData, URLSafeTimedSerializer
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
TOKEN_MAX_AGE = 28800
|
||||
TOKEN_SALT = "auth-lite-session-v1"
|
||||
|
||||
|
||||
def normalize_username(value: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("username must be a string")
|
||||
value = value.strip().lower()
|
||||
if not re.fullmatch(r"[a-z0-9._-]{3,64}", value):
|
||||
raise ValueError("username must contain 3-64 characters from [a-z0-9._-]")
|
||||
return value
|
||||
|
||||
|
||||
def validate_password(value: str, minimum: int = 1) -> str:
|
||||
if not isinstance(value, str) or not minimum <= len(value) <= 128:
|
||||
raise ValueError(f"password must contain {minimum}-128 characters")
|
||||
return value
|
||||
|
||||
|
||||
def validate_auth_storage() -> None:
|
||||
from persistance.db import get_auth_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
try:
|
||||
url = make_url(settings.auth_database_url)
|
||||
if url.get_backend_name() != "sqlite":
|
||||
raise ValueError("SQLite required")
|
||||
if not url.database or url.database == ":memory:" or not Path(url.database).is_file():
|
||||
raise ValueError("existing SQLite required")
|
||||
engine = get_auth_engine()
|
||||
if not {"user", "role", "user_role", "alembic_version"} <= set(inspect(engine).get_table_names()):
|
||||
raise ValueError("migration required")
|
||||
# Validate the columns needed by login/bootstrap, without creating schema.
|
||||
from sqlalchemy import text
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT id, username, password_hash, activo FROM user LIMIT 0"))
|
||||
connection.execute(text("SELECT code FROM role LIMIT 0"))
|
||||
connection.execute(text("SELECT user_id, role_code FROM user_role LIMIT 0"))
|
||||
except Exception:
|
||||
if get_auth_engine.cache_info().currsize:
|
||||
get_auth_engine().dispose()
|
||||
get_auth_engine.cache_clear()
|
||||
raise ValueError("Auth-Lite storage must be an accessible migrated SQLite database") from None
|
||||
|
||||
|
||||
def serializer(secret: str) -> URLSafeTimedSerializer:
|
||||
return URLSafeTimedSerializer(secret, salt=TOKEN_SALT)
|
||||
|
||||
|
||||
def issue_token(secret: str, user_id: int) -> str:
|
||||
return serializer(secret).dumps({"user_id": user_id, "v": 1})
|
||||
|
||||
|
||||
def read_token(secret: str, token: str) -> int | None:
|
||||
try:
|
||||
payload = serializer(secret).loads(token, max_age=TOKEN_MAX_AGE)
|
||||
except BadData:
|
||||
return None
|
||||
if not isinstance(payload, dict) or set(payload) != {"user_id", "v"}:
|
||||
return None
|
||||
if type(payload["v"]) is not int or payload["v"] != 1:
|
||||
return None
|
||||
user_id = payload["user_id"]
|
||||
return user_id if type(user_id) is int and 0 < user_id <= 9223372036854775807 else None
|
||||
|
||||
|
||||
def user_dto(user, roles: list[str]) -> dict:
|
||||
return {"id": user.id, "username": user.username, "roles": sorted(roles)}
|
||||
@@ -0,0 +1,44 @@
|
||||
from flask import Blueprint, current_app, request
|
||||
from werkzeug.security import check_password_hash
|
||||
|
||||
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
|
||||
from webapi.auth_token import (
|
||||
TOKEN_MAX_AGE, issue_token, normalize_username, read_token, user_dto, validate_password,
|
||||
)
|
||||
|
||||
auth_bp = Blueprint("auth", __name__)
|
||||
|
||||
|
||||
@auth_bp.post("/login")
|
||||
def login():
|
||||
body = request.get_json(silent=True)
|
||||
try:
|
||||
if not isinstance(body, dict):
|
||||
raise ValueError("JSON object required")
|
||||
username = normalize_username(body.get("username"))
|
||||
password = validate_password(body.get("password"))
|
||||
except ValueError:
|
||||
return {"error": "invalid_request"}, 400
|
||||
user = get_user_by_username(username)
|
||||
if user is None or not user.activo or not check_password_hash(user.password_hash, password):
|
||||
return {"error": "invalid_credentials"}, 401
|
||||
identity = get_user_with_roles_by_id(user.id)
|
||||
if identity is None or not identity[0].activo:
|
||||
return {"error": "invalid_credentials"}, 401
|
||||
return {
|
||||
"token": issue_token(current_app.config["AUTH_LITE_SECRET_KEY"], user.id),
|
||||
"expires_in": TOKEN_MAX_AGE,
|
||||
"user": user_dto(*identity),
|
||||
}
|
||||
|
||||
|
||||
@auth_bp.get("/me")
|
||||
def me():
|
||||
parts = request.headers.get("Authorization", "").split()
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
return {"error": "unauthorized"}, 401
|
||||
user_id = read_token(current_app.config["AUTH_LITE_SECRET_KEY"], parts[1])
|
||||
identity = get_user_with_roles_by_id(user_id) if user_id is not None else None
|
||||
if identity is None or not identity[0].activo:
|
||||
return {"error": "unauthorized"}, 401
|
||||
return {"user": user_dto(*identity)}
|
||||
Reference in New Issue
Block a user