feat(auth): implementar soporte de autenticacion en WebApi
This commit is contained in:
@@ -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())
|
||||
Reference in New Issue
Block a user