files-server-fastapi 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. files_server_fastapi-0.1.0/.gitignore +207 -0
  2. files_server_fastapi-0.1.0/.python-version +1 -0
  3. files_server_fastapi-0.1.0/LICENSE +21 -0
  4. files_server_fastapi-0.1.0/MANIFEST.in +2 -0
  5. files_server_fastapi-0.1.0/PKG-INFO +41 -0
  6. files_server_fastapi-0.1.0/README.md +2 -0
  7. files_server_fastapi-0.1.0/pyproject.toml +44 -0
  8. files_server_fastapi-0.1.0/src/files_server_fastapi/__init__.py +20 -0
  9. files_server_fastapi-0.1.0/src/files_server_fastapi/models/__init__.py +16 -0
  10. files_server_fastapi-0.1.0/src/files_server_fastapi/models/area_model.py +10 -0
  11. files_server_fastapi-0.1.0/src/files_server_fastapi/models/permisos_model.py +31 -0
  12. files_server_fastapi-0.1.0/src/files_server_fastapi/models/rol_model.py +14 -0
  13. files_server_fastapi-0.1.0/src/files_server_fastapi/models/rutas_model.py +16 -0
  14. files_server_fastapi-0.1.0/src/files_server_fastapi/models/users_extend_model.py +11 -0
  15. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/__init__.py +16 -0
  16. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/area_router.py +26 -0
  17. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/files_router.py +123 -0
  18. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/permisos_router.py +36 -0
  19. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/rol_router.py +20 -0
  20. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/rutas_router.py +20 -0
  21. files_server_fastapi-0.1.0/src/files_server_fastapi/routers/users_extend_router.py +33 -0
  22. files_server_fastapi-0.1.0/uv.lock +1653 -0
@@ -0,0 +1,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
@@ -0,0 +1 @@
1
+ 3.13.9
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aldo Blancas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include LICENSE
2
+ include README.md
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: files-server-fastapi
3
+ Version: 0.1.0
4
+ Summary: Este repositorio es un paquete python desarrollado con FastAPI, gestiona la comunicación con un servidor Samba y utiliza PostgreSQL para administrar rutas de archivos y el control de acceso basado en roles (RBAC) de los usuarios.
5
+ Project-URL: Homepage, https://github.com/AldoBP/files-server-fastapi
6
+ Project-URL: Repository, https://github.com/AldoBP/files-server-fastapi
7
+ Project-URL: Issues, https://github.com/AldoBP/files-server-fastapi/issues
8
+ Author: Aldo Blancas
9
+ License: MIT License
10
+
11
+ Copyright (c) 2026 Aldo Blancas
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Keywords: fastapi,fileserver,postgresql,rbac,samba
32
+ Classifier: Framework :: FastAPI
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Programming Language :: Python :: 3.10
36
+ Requires-Python: >=3.10
37
+ Requires-Dist: oauth2fast-fastapi==0.2.2
38
+ Description-Content-Type: text/markdown
39
+
40
+ # files-server-fastapi
41
+ Este repositorio es un paquete python desarrollado con FastAPI, gestiona la comunicación con un servidor Samba y utiliza PostgreSQL para administrar rutas de archivos y el control de acceso basado en roles (RBAC) de los usuarios.
@@ -0,0 +1,2 @@
1
+ # files-server-fastapi
2
+ Este repositorio es un paquete python desarrollado con FastAPI, gestiona la comunicación con un servidor Samba y utiliza PostgreSQL para administrar rutas de archivos y el control de acceso basado en roles (RBAC) de los usuarios.
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "files-server-fastapi"
3
+ version = "0.1.0"
4
+ description = "Este repositorio es un paquete python desarrollado con FastAPI, gestiona la comunicación con un servidor Samba y utiliza PostgreSQL para administrar rutas de archivos y el control de acceso basado en roles (RBAC) de los usuarios."
5
+ readme = "README.md"
6
+ license = { file = "LICENSE" }
7
+ authors = [
8
+ { name = "Aldo Blancas" },
9
+ ]
10
+ keywords = ["fastapi", "samba", "fileserver", "rbac", "postgresql"]
11
+ classifiers = [
12
+ "License :: OSI Approved :: MIT License",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.10",
15
+ "Framework :: FastAPI",
16
+ ]
17
+ requires-python = ">=3.10"
18
+ dependencies = [
19
+ "oauth2fast-fastapi==0.2.2",
20
+ ]
21
+
22
+ [dependency-groups]
23
+ dev = [
24
+ "build",
25
+ "twine",
26
+ ]
27
+
28
+ test = [
29
+ "pytest",
30
+ "pytest-cov",
31
+ ]
32
+
33
+ [build-system]
34
+ requires = ["hatchling"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/AldoBP/files-server-fastapi"
39
+ Repository = "https://github.com/AldoBP/files-server-fastapi"
40
+ Issues = "https://github.com/AldoBP/files-server-fastapi/issues"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/files_server_fastapi"]
44
+
@@ -0,0 +1,20 @@
1
+ # files_server_fastapi/__init__.py
2
+ # Exporta todos los routers para que main.py pueda importarlos directamente.
3
+
4
+ from files_server_fastapi.routers import (
5
+ area_router,
6
+ rol_router,
7
+ rutas_router,
8
+ permisos_router,
9
+ users_extend_router,
10
+ files_router,
11
+ )
12
+
13
+ __all__ = [
14
+ "area_router",
15
+ "rol_router",
16
+ "rutas_router",
17
+ "permisos_router",
18
+ "users_extend_router",
19
+ "files_router",
20
+ ]
@@ -0,0 +1,16 @@
1
+ # models/__init__.py
2
+ from .area_model import Area
3
+ from .rol_model import Rol
4
+ from .rutas_model import Rutas
5
+ from .permisos_model import Permisos, Permiso_user, Permiso_rol
6
+ from .users_extend_model import Users_extend
7
+
8
+ __all__ = [
9
+ "Area",
10
+ "Rol",
11
+ "Rutas",
12
+ "Permisos",
13
+ "Permiso_user",
14
+ "Permiso_rol",
15
+ "Users_extend",
16
+ ]
@@ -0,0 +1,10 @@
1
+ from typing import Optional
2
+ from sqlmodel import Field
3
+ from oauth2fast_fastapi import AuthModel
4
+
5
+ class Area(AuthModel, table=True):
6
+ __tablename__ = "area"
7
+
8
+ id: Optional[int] = Field(default=None, primary_key=True)
9
+ area_name: str = Field(nullable=False)
10
+ description: Optional[str] = Field(default=None)
@@ -0,0 +1,31 @@
1
+ from typing import Optional
2
+ from sqlmodel import Field
3
+ from oauth2fast_fastapi import AuthModel
4
+
5
+ # Catálogo principal de permisos
6
+ class Permisos(AuthModel, table=True):
7
+ __tablename__ = "permisos"
8
+
9
+ id: Optional[int] = Field(default=None, primary_key=True)
10
+ permiso_name: str = Field(nullable=False)
11
+ description: Optional[str] = Field(default=None)
12
+
13
+
14
+ # Tabla intermedia: Permisos por Usuario
15
+ class Permiso_user(AuthModel, table=True):
16
+ __tablename__ = "permiso_user"
17
+
18
+ id: Optional[int] = Field(default=None, primary_key=True)
19
+ id_user: int = Field(foreign_key="users.id")
20
+ id_permiso: int = Field(foreign_key="permisos.id")
21
+ ruta_id: int = Field(foreign_key="rutas.id")
22
+
23
+
24
+ # Tabla intermedia: Permisos por Rol
25
+ class Permiso_rol(AuthModel, table=True):
26
+ __tablename__ = "permiso_rol"
27
+
28
+ id: Optional[int] = Field(default=None, primary_key=True)
29
+ id_rol: int = Field(foreign_key="rol.id")
30
+ id_permiso: int = Field(foreign_key="permisos.id")
31
+ ruta_id: int = Field(foreign_key="rutas.id")
@@ -0,0 +1,14 @@
1
+ from typing import Optional
2
+ from datetime import datetime, timezone
3
+ from sqlmodel import Field
4
+ from oauth2fast_fastapi import AuthModel
5
+
6
+ def get_utc_now():
7
+ return datetime.now(timezone.utc)
8
+
9
+ class Rol(AuthModel, table=True):
10
+ __tablename__ = "rol"
11
+
12
+ id: Optional[int] = Field(default=None, primary_key=True)
13
+ role_name: str = Field(nullable=False)
14
+ description: Optional[str] = Field(default=None)
@@ -0,0 +1,16 @@
1
+ from typing import Optional
2
+ from sqlmodel import Field
3
+ from oauth2fast_fastapi import AuthModel
4
+
5
+ class Rutas(AuthModel, table=True):
6
+ __tablename__ = "rutas"
7
+
8
+ id: Optional[int] = Field(default=None, primary_key=True)
9
+ ruta: str = Field(nullable=False)
10
+ name: str = Field(nullable=False)
11
+
12
+ # Llave foránea hacia Area
13
+ area_id: int = Field(foreign_key="area.id")
14
+
15
+ # Auto-referencia para sub-rutas (puede ser nula si es ruta principal)
16
+ ruta_id: Optional[int] = Field(default=None, foreign_key="rutas.id")
@@ -0,0 +1,11 @@
1
+ from sqlmodel import Field
2
+ from oauth2fast_fastapi import AuthModel
3
+
4
+ class Users_extend(AuthModel, table=True):
5
+ __tablename__ = "users_extend"
6
+
7
+ # Es Primary Key y Foreign Key al mismo tiempo (Relación 1 a 1)
8
+ user_id: int = Field(primary_key=True, foreign_key="users.id")
9
+
10
+ area_id: int = Field(foreign_key="area.id")
11
+ rol_id: int = Field(foreign_key="rol.id")
@@ -0,0 +1,16 @@
1
+ # routers/__init__.py
2
+ from files_server_fastapi.routers import area_router
3
+ from files_server_fastapi.routers import rol_router
4
+ from files_server_fastapi.routers import rutas_router
5
+ from files_server_fastapi.routers import permisos_router
6
+ from files_server_fastapi.routers import users_extend_router
7
+ from files_server_fastapi.routers import files_router
8
+
9
+ __all__ = [
10
+ "area_router",
11
+ "rol_router",
12
+ "rutas_router",
13
+ "permisos_router",
14
+ "users_extend_router",
15
+ "files_router",
16
+ ]
@@ -0,0 +1,26 @@
1
+ from fastapi import APIRouter, Depends
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy import select
4
+
5
+ from pgsqlasync2fast_fastapi.dependencies import get_db_session
6
+ from files_server_fastapi.models.area_model import Area
7
+
8
+ router = APIRouter(prefix="/areas", tags=["Gestión de Áreas"])
9
+
10
+ @router.post("/", response_model=Area, summary="Crear una nueva Área")
11
+ async def create_area(area: Area, db: AsyncSession = Depends(get_db_session)):
12
+ """
13
+ Guarda una nueva área en la base de datos.
14
+ """
15
+ db.add(area)
16
+ await db.commit()
17
+ await db.refresh(area)
18
+ return area
19
+
20
+ @router.get("/", response_model=list[Area], summary="Obtener todas las Áreas")
21
+ async def get_areas(db: AsyncSession = Depends(get_db_session)):
22
+ """
23
+ Devuelve la lista de todas las áreas registradas.
24
+ """
25
+ result = await db.execute(select(Area))
26
+ return result.scalars().all()
@@ -0,0 +1,123 @@
1
+ import os
2
+ from fastapi import APIRouter, HTTPException
3
+ from datetime import datetime
4
+ from pydantic import BaseModel
5
+
6
+ router = APIRouter(prefix="/files", tags=["Archivos del Sistema"])
7
+
8
+ # Directorio maestro (La ruta de red de Samba vista desde Windows)
9
+ BASE_DIR = r"\\192.168.1.122\Compartido"
10
+
11
+ @router.get("/list", summary="Listar archivos de una carpeta")
12
+ async def list_directory(area: str, subpath: str = "/"):
13
+ # Seguridad básica: Evitar que un hacker suba de nivel con "../"
14
+ if ".." in subpath:
15
+ raise HTTPException(status_code=400, detail="Ruta inválida")
16
+
17
+ safe_subpath = subpath.strip("/")
18
+
19
+ if safe_subpath == "":
20
+ ruta_real = os.path.join(BASE_DIR, area.upper())
21
+ else:
22
+ ruta_real = os.path.join(BASE_DIR, area.upper(), safe_subpath)
23
+
24
+ if not os.path.exists(ruta_real):
25
+ return []
26
+
27
+ if not os.path.isdir(ruta_real):
28
+ raise HTTPException(status_code=400, detail="La ruta no es un directorio")
29
+
30
+ items = []
31
+ try:
32
+ with os.scandir(ruta_real) as ficheros:
33
+ for fichero in ficheros:
34
+ info = fichero.stat()
35
+ fecha_mod = datetime.fromtimestamp(info.st_mtime).strftime("%Y-%m-%d %H:%M")
36
+
37
+ if fichero.is_dir():
38
+ items.append({
39
+ "name": fichero.name,
40
+ "type": "folder",
41
+ "updated": fecha_mod,
42
+ "size": "",
43
+ "locked": False
44
+ })
45
+ else:
46
+ size_kb = info.st_size / 1024
47
+ size_str = f"{size_kb:.1f} KB" if size_kb < 1024 else f"{size_kb/1024:.1f} MB"
48
+ items.append({
49
+ "name": fichero.name,
50
+ "type": "file",
51
+ "updated": fecha_mod,
52
+ "size": size_str,
53
+ "locked": False
54
+ })
55
+
56
+ items.sort(key=lambda x: (x["type"] == "file", x["name"].lower()))
57
+ return items
58
+
59
+ except PermissionError:
60
+ raise HTTPException(status_code=403, detail="Acceso denegado por el sistema operativo")
61
+
62
+
63
+ # ==========================================
64
+ # RUTAS: CREAR CARPETAS
65
+ # ==========================================
66
+
67
+ class FolderCreate(BaseModel):
68
+ area: str
69
+ subpath: str
70
+ folder_name: str
71
+
72
+ @router.post("/folder", summary="Crear una nueva carpeta en el servidor")
73
+ async def create_folder(req: FolderCreate):
74
+ if ".." in req.subpath or ".." in req.folder_name or "/" in req.folder_name:
75
+ raise HTTPException(status_code=400, detail="Nombre de carpeta o ruta inválida")
76
+
77
+ safe_subpath = req.subpath.strip("/")
78
+
79
+ if safe_subpath == "":
80
+ ruta_final = os.path.join(BASE_DIR, req.area.upper(), req.folder_name)
81
+ else:
82
+ ruta_final = os.path.join(BASE_DIR, req.area.upper(), safe_subpath, req.folder_name)
83
+
84
+ try:
85
+ os.makedirs(ruta_final, exist_ok=False)
86
+ return {"message": "Carpeta creada exitosamente", "path": ruta_final}
87
+ except FileExistsError:
88
+ raise HTTPException(status_code=400, detail="Ya existe una carpeta con ese nombre aquí")
89
+ except PermissionError:
90
+ raise HTTPException(status_code=403, detail="El servidor rechazó el permiso de escritura")
91
+ except Exception as e:
92
+ raise HTTPException(status_code=500, detail=str(e))
93
+
94
+
95
+ # ==========================================
96
+ # RUTA: ESCANEAR EL ÁRBOL DE CARPETAS
97
+ # ==========================================
98
+
99
+ def get_directory_tree(path_to_scan, base_name=""):
100
+ """Función recursiva de Python para leer subcarpetas"""
101
+ tree = []
102
+ try:
103
+ with os.scandir(path_to_scan) as entries:
104
+ for entry in entries:
105
+ if entry.is_dir():
106
+ relative_path = os.path.join(base_name, entry.name).replace("\\", "/")
107
+ tree.append({
108
+ "name": entry.name,
109
+ "path": f"/{relative_path}",
110
+ "children": get_directory_tree(entry.path, relative_path)
111
+ })
112
+ except PermissionError:
113
+ pass
114
+ return sorted(tree, key=lambda x: x["name"].lower())
115
+
116
+ @router.get("/tree", summary="Obtener el árbol de carpetas de un área")
117
+ async def get_area_tree(area: str):
118
+ area_path = os.path.join(BASE_DIR, area.upper())
119
+
120
+ if not os.path.exists(area_path):
121
+ return []
122
+
123
+ return get_directory_tree(area_path)
@@ -0,0 +1,36 @@
1
+ from fastapi import APIRouter, Depends
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy import select
4
+
5
+ from pgsqlasync2fast_fastapi.dependencies import get_db_session
6
+ from files_server_fastapi.models.permisos_model import Permisos, Permiso_user, Permiso_rol
7
+
8
+ router = APIRouter(prefix="/permisos", tags=["Gestión de Permisos"])
9
+
10
+ # --- Catálogo Maestro ---
11
+ @router.post("/", response_model=Permisos, summary="Crear Permiso Maestro")
12
+ async def create_permiso(permiso: Permisos, db: AsyncSession = Depends(get_db_session)):
13
+ db.add(permiso)
14
+ await db.commit()
15
+ await db.refresh(permiso)
16
+ return permiso
17
+
18
+ @router.get("/", response_model=list[Permisos], summary="Ver Permisos Maestros")
19
+ async def get_permisos(db: AsyncSession = Depends(get_db_session)):
20
+ result = await db.execute(select(Permisos))
21
+ return result.scalars().all()
22
+
23
+ # --- Asignaciones Intermedias ---
24
+ @router.post("/asignar-usuario", response_model=Permiso_user, summary="Asignar permiso a un Usuario")
25
+ async def assign_user(permiso: Permiso_user, db: AsyncSession = Depends(get_db_session)):
26
+ db.add(permiso)
27
+ await db.commit()
28
+ await db.refresh(permiso)
29
+ return permiso
30
+
31
+ @router.post("/asignar-rol", response_model=Permiso_rol, summary="Asignar permiso a un Rol")
32
+ async def assign_rol(permiso: Permiso_rol, db: AsyncSession = Depends(get_db_session)):
33
+ db.add(permiso)
34
+ await db.commit()
35
+ await db.refresh(permiso)
36
+ return permiso
@@ -0,0 +1,20 @@
1
+ from fastapi import APIRouter, Depends
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy import select
4
+
5
+ from pgsqlasync2fast_fastapi.dependencies import get_db_session
6
+ from files_server_fastapi.models.rol_model import Rol
7
+
8
+ router = APIRouter(prefix="/roles", tags=["Gestión de Roles"])
9
+
10
+ @router.post("/", response_model=Rol, summary="Crear un nuevo Rol")
11
+ async def create_rol(rol: Rol, db: AsyncSession = Depends(get_db_session)):
12
+ db.add(rol)
13
+ await db.commit()
14
+ await db.refresh(rol)
15
+ return rol
16
+
17
+ @router.get("/", response_model=list[Rol], summary="Obtener todos los Roles")
18
+ async def get_roles(db: AsyncSession = Depends(get_db_session)):
19
+ result = await db.execute(select(Rol))
20
+ return result.scalars().all()