Initial monorepo structure
@@ -0,0 +1 @@
|
||||
"""App package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""API package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""API v1 package."""
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Auth routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import get_password_hash, verify_password, create_access_token, decode_token
|
||||
from app.core.auth import get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.associations import UserRole, UserModuleRole, ModuleRole
|
||||
from app.models.role import Role
|
||||
from app.schemas.schemas import RegisterRequest, LoginRequest, TokenResponse, UserResponse
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserResponse, status_code=201)
|
||||
async def register(data: RegisterRequest, db: Session = Depends(get_db)):
|
||||
if db.query(User).filter(User.email == data.email).first():
|
||||
raise HTTPException(status_code=409, detail="Email already registered")
|
||||
user = User(
|
||||
email=data.email,
|
||||
password_hash=get_password_hash(data.password),
|
||||
first_name=data.first_name,
|
||||
last_name=data.last_name,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
async def login(data: LoginRequest, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.email == data.email).first()
|
||||
if not user or not verify_password(data.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid email or password")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="User is deactivated")
|
||||
|
||||
user_data = _build_user_response(user, db)
|
||||
token = create_access_token(data={
|
||||
"sub": str(user.id),
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": user_data["roles"],
|
||||
"module_roles": user_data["module_roles"],
|
||||
})
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "bearer",
|
||||
"expires_in": 28800,
|
||||
"user": user_data,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/validate")
|
||||
async def validate_token(token: str = None, db: Session = Depends(get_db)):
|
||||
"""Validate JWT for modules. Token passed as query param or body."""
|
||||
from fastapi import Request
|
||||
# Modules call this endpoint with the JWT
|
||||
# We just decode and return user data
|
||||
if not token:
|
||||
raise HTTPException(status_code=400, detail="Token required")
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
user = db.query(User).filter(User.id == int(user_id)).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
user_data = _build_user_response(user, db)
|
||||
return {"user_id": user.id, **user_data}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return _build_user_response(user, db)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Health routes."""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter(tags=["Health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health():
|
||||
return {"status": "healthy", "service": "Platform"}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Modules routes."""
|
||||
|
||||
import secrets
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
import httpx
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import require_platform_admin
|
||||
from app.models.user import User
|
||||
from app.models.module import Module
|
||||
from app.models.associations import ModuleRole
|
||||
from app.schemas.schemas import ModuleCreate, ModuleResponse, ModuleRoleResponse
|
||||
|
||||
router = APIRouter(prefix="/modules", tags=["Modules"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_modules(db: Session = Depends(get_db)):
|
||||
modules = db.query(Module).order_by(Module.name).all()
|
||||
return [
|
||||
{
|
||||
"id": m.id, "name": m.name, "slug": m.slug, "description": m.description,
|
||||
"url": m.url, "icon": m.icon, "is_active": m.is_active,
|
||||
"roles_count": len(m.module_roles),
|
||||
}
|
||||
for m in modules
|
||||
]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_module(data: ModuleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
if db.query(Module).filter(Module.slug == data.slug).first():
|
||||
raise HTTPException(status_code=409, detail="Module slug already exists")
|
||||
module = Module(
|
||||
name=data.name,
|
||||
slug=data.slug,
|
||||
description=data.description,
|
||||
url=data.url,
|
||||
icon=data.icon,
|
||||
api_key=secrets.token_hex(32),
|
||||
)
|
||||
db.add(module)
|
||||
db.commit()
|
||||
db.refresh(module)
|
||||
return {
|
||||
"id": module.id, "name": module.name, "slug": module.slug, "description": module.description,
|
||||
"url": module.url, "icon": module.icon, "is_active": module.is_active, "api_key": module.api_key,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{module_id}")
|
||||
async def update_module(module_id: int, data: ModuleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
module.name = data.name
|
||||
module.slug = data.slug
|
||||
module.description = data.description
|
||||
module.url = data.url
|
||||
module.icon = data.icon
|
||||
db.commit()
|
||||
return {
|
||||
"id": module.id, "name": module.name, "slug": module.slug, "description": module.description,
|
||||
"url": module.url, "icon": module.icon, "is_active": module.is_active, "api_key": module.api_key,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{module_id}")
|
||||
async def delete_module(module_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
db.delete(module)
|
||||
db.commit()
|
||||
return {"message": "Module deleted"}
|
||||
|
||||
|
||||
@router.post("/{module_id}/sync-roles")
|
||||
async def sync_roles(module_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
"""Import roles from module and sync all users."""
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
|
||||
# 1. Sync roles
|
||||
try:
|
||||
resp = httpx.get(f"{module.url.rstrip('/')}/api/v1/reference/roles", timeout=10)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=502, detail=f"Module returned {resp.status_code}")
|
||||
roles_data = resp.json()
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Cannot reach module: {e}")
|
||||
|
||||
# Clear old roles for this module
|
||||
db.query(ModuleRole).filter(ModuleRole.module_id == module_id).delete()
|
||||
|
||||
imported = 0
|
||||
for r in roles_data:
|
||||
role_name = r.get("name") if isinstance(r, dict) else r
|
||||
desc = r.get("description") if isinstance(r, dict) else None
|
||||
db.add(ModuleRole(module_id=module_id, role_name=role_name, description=desc))
|
||||
imported += 1
|
||||
|
||||
db.commit()
|
||||
|
||||
# 2. Sync all users to module
|
||||
from app.api.v1.users import _sync_all_users_to_modules
|
||||
_sync_all_users_to_modules(db)
|
||||
|
||||
return {
|
||||
"message": f"Imported {imported} roles and synced users",
|
||||
"roles": [r.get("name", r) if isinstance(r, dict) else r for r in roles_data],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{module_id}/roles")
|
||||
async def get_module_roles(module_id: int, db: Session = Depends(get_db)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
return [
|
||||
{"id": mr.id, "module_id": mr.module_id, "role_name": mr.role_name, "description": mr.description}
|
||||
for mr in module.module_roles
|
||||
]
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Roles routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import require_platform_admin
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.schemas.schemas import RoleCreate, RoleResponse
|
||||
|
||||
router = APIRouter(prefix="/roles", tags=["Roles"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_roles(db: Session = Depends(get_db)):
|
||||
roles = db.query(Role).order_by(Role.name).all()
|
||||
return [{"id": r.id, "name": r.name, "description": r.description, "is_system": r.is_system} for r in roles]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_role(data: RoleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
if db.query(Role).filter(Role.name == data.name).first():
|
||||
raise HTTPException(status_code=409, detail="Role already exists")
|
||||
role = Role(name=data.name, description=data.description)
|
||||
db.add(role)
|
||||
db.commit()
|
||||
db.refresh(role)
|
||||
return {"id": role.id, "name": role.name, "description": role.description, "is_system": role.is_system}
|
||||
|
||||
|
||||
@router.put("/{role_id}")
|
||||
async def update_role(role_id: int, data: RoleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
if role.is_system:
|
||||
raise HTTPException(status_code=400, detail="Cannot modify system role")
|
||||
role.name = data.name
|
||||
role.description = data.description
|
||||
db.commit()
|
||||
return {"id": role.id, "name": role.name, "description": role.description, "is_system": role.is_system}
|
||||
|
||||
|
||||
@router.delete("/{role_id}")
|
||||
async def delete_role(role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
if role.is_system:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete system role")
|
||||
db.delete(role)
|
||||
db.commit()
|
||||
return {"message": "Role deleted"}
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Users routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
import httpx
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import get_current_user, require_platform_admin
|
||||
from app.core.security import get_password_hash, create_access_token
|
||||
from app.models.user import User
|
||||
from app.models.associations import UserRole, ModuleRole, UserModuleRole
|
||||
from app.models.role import Role
|
||||
from app.models.module import Module
|
||||
from app.schemas.schemas import UserResponse, UserListResponse, RoleResponse
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["Users"])
|
||||
|
||||
|
||||
def _sync_user_to_modules(db: Session, user: User):
|
||||
"""Push user data to all active modules."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
|
||||
# Build module roles mapping for this user
|
||||
module_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
module_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
|
||||
for mod in modules:
|
||||
# Get roles specific to this module
|
||||
roles_for_module = module_roles.get(mod.slug, [])
|
||||
|
||||
user_data = {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": roles_for_module,
|
||||
}
|
||||
|
||||
try:
|
||||
httpx.post(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/sync",
|
||||
json=user_data,
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=5,
|
||||
)
|
||||
except Exception:
|
||||
pass # Module may be offline, that's OK
|
||||
|
||||
|
||||
def _sync_user_deletion_to_modules(db: Session, user: User):
|
||||
"""Notify modules about user deletion."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
for mod in modules:
|
||||
try:
|
||||
httpx.delete(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/{user.id}",
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _sync_all_users_to_modules(db: Session):
|
||||
"""Sync all users to all active modules."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
users = db.query(User).filter(User.is_active == True).all()
|
||||
user_data_list = [
|
||||
{
|
||||
"id": u.id,
|
||||
"email": u.email,
|
||||
"first_name": u.first_name,
|
||||
"last_name": u.last_name,
|
||||
"is_active": u.is_active,
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
for mod in modules:
|
||||
try:
|
||||
httpx.post(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/sync-all",
|
||||
json={"users": user_data_list},
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=10,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_model=UserListResponse)
|
||||
async def list_users(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
search: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
query = db.query(User)
|
||||
if search:
|
||||
term = f"%{search}%"
|
||||
query = query.filter(User.email.ilike(term) | User.first_name.ilike(term) | User.last_name.ilike(term))
|
||||
total = query.count()
|
||||
users = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {
|
||||
"users": [_build_user_response(u, db) for u in users],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
async def get_user(user_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_user(
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
first_name = data.get("first_name", "")
|
||||
last_name = data.get("last_name", "")
|
||||
|
||||
if not email or not password:
|
||||
raise HTTPException(status_code=400, detail="email and password required")
|
||||
|
||||
if db.query(User).filter(User.email == email).first():
|
||||
raise HTTPException(status_code=409, detail="Email already exists")
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
password_hash=get_password_hash(password),
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
is_superadmin=data.get("is_superadmin", False),
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Assign roles if provided
|
||||
for role_id in data.get("role_ids", []):
|
||||
db.add(UserRole(user_id=user.id, role_id=role_id))
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Sync to modules
|
||||
_sync_user_to_modules(db, user)
|
||||
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.put("/{user_id}")
|
||||
async def update_user(
|
||||
user_id: int,
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
if "first_name" in data:
|
||||
user.first_name = data["first_name"]
|
||||
if "last_name" in data:
|
||||
user.last_name = data["last_name"]
|
||||
if "email" in data:
|
||||
existing = db.query(User).filter(User.email == data["email"], User.id != user_id).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="Email already exists")
|
||||
user.email = data["email"]
|
||||
if "is_active" in data:
|
||||
user.is_active = data["is_active"]
|
||||
if "is_superadmin" in data:
|
||||
user.is_superadmin = data["is_superadmin"]
|
||||
if "password" in data and data["password"]:
|
||||
user.password_hash = get_password_hash(data["password"])
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Sync to modules
|
||||
_sync_user_to_modules(db, user)
|
||||
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
if user.is_superadmin:
|
||||
raise HTTPException(status_code=403, detail="Cannot delete superadmin")
|
||||
|
||||
# Notify modules about deletion
|
||||
_sync_user_deletion_to_modules(db, user)
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return {"message": "User deleted"}
|
||||
|
||||
|
||||
@router.get("/{user_id}/roles")
|
||||
async def get_user_roles(user_id: int, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"roles": [ur.role.name for ur in user.user_roles if ur.role]}
|
||||
|
||||
|
||||
@router.post("/{user_id}/roles/{role_id}")
|
||||
async def assign_role(user_id: int, role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
existing = db.query(UserRole).filter(UserRole.user_id == user_id, UserRole.role_id == role_id).first()
|
||||
if not existing:
|
||||
db.add(UserRole(user_id=user_id, role_id=role_id))
|
||||
db.commit()
|
||||
return {"message": "Role assigned"}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/roles/{role_id}")
|
||||
async def remove_role(user_id: int, role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
ur = db.query(UserRole).filter(UserRole.user_id == user_id, UserRole.role_id == role_id).first()
|
||||
if ur:
|
||||
db.delete(ur)
|
||||
db.commit()
|
||||
return {"message": "Role removed"}
|
||||
|
||||
|
||||
@router.get("/{user_id}/module-roles")
|
||||
async def get_user_module_roles(user_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
result = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
result.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {"module_roles": result}
|
||||
|
||||
|
||||
@router.post("/{user_id}/module-roles/{module_role_id}")
|
||||
async def assign_module_role(user_id: int, module_role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
existing = db.query(UserModuleRole).filter(UserModuleRole.user_id == user_id, UserModuleRole.module_role_id == module_role_id).first()
|
||||
if not existing:
|
||||
db.add(UserModuleRole(user_id=user_id, module_role_id=module_role_id))
|
||||
db.commit()
|
||||
|
||||
# Sync user with updated roles to the module
|
||||
_sync_user_to_modules(db, db.query(User).filter(User.id == user_id).first())
|
||||
|
||||
return {"message": "Module role assigned"}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/module-roles/{module_role_id}")
|
||||
async def remove_module_role(user_id: int, module_role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
umr = db.query(UserModuleRole).filter(UserModuleRole.user_id == user_id, UserModuleRole.module_role_id == module_role_id).first()
|
||||
if umr:
|
||||
db.delete(umr)
|
||||
db.commit()
|
||||
|
||||
# Sync user with updated roles to the module
|
||||
_sync_user_to_modules(db, db.query(User).filter(User.id == user_id).first())
|
||||
|
||||
return {"message": "Module role removed"}
|
||||
@@ -0,0 +1 @@
|
||||
"""Core package."""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Auth dependencies."""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import decode_token
|
||||
from app.models.user import User
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security)) -> int:
|
||||
token = credentials.credentials
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is deactivated")
|
||||
return user
|
||||
|
||||
|
||||
def require_platform_admin(user: User = Depends(get_current_user), db: Session = Depends(get_db)) -> User:
|
||||
if user.is_superadmin:
|
||||
return user
|
||||
from app.models.associations import UserRole
|
||||
from app.models.role import Role
|
||||
has_role = db.query(UserRole).join(Role).filter(
|
||||
UserRole.user_id == user.id, Role.name == "platform_admin"
|
||||
).first()
|
||||
if not has_role:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Platform admin required")
|
||||
return user
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Database utilities."""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from typing import Generator
|
||||
from app.settings import get_settings
|
||||
from app.models.base import Base
|
||||
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.DATABASE_URL, pool_pre_ping=True, echo=False)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
from app.models import user, role, module, associations
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
from app.models.role import Role
|
||||
system_roles = [
|
||||
("platform_admin", "Platform administrator", True),
|
||||
("user_manager", "Can manage users", True),
|
||||
]
|
||||
for name, desc, is_system in system_roles:
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=desc, is_system=is_system))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Security utilities."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from app.settings import get_settings
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=get_settings().JWT_ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, get_settings().JWT_SECRET_KEY, algorithm=get_settings().JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
return jwt.decode(token, get_settings().JWT_SECRET_KEY, algorithms=[get_settings().JWT_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Platform - Main Application."""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.settings import get_settings
|
||||
from app.core.database import init_db
|
||||
from app.api.v1 import auth, users, roles, modules, health
|
||||
|
||||
app = FastAPI(
|
||||
title=get_settings().APP_NAME,
|
||||
version=get_settings().APP_VERSION,
|
||||
description="Platform - Module Management System",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# CORS
|
||||
cors_origins = get_settings().APP_CORS_ORIGINS.split(",")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Routes
|
||||
app.include_router(health.router, prefix="/api/v1")
|
||||
app.include_router(auth.router, prefix="/api/v1")
|
||||
app.include_router(users.router, prefix="/api/v1")
|
||||
app.include_router(roles.router, prefix="/api/v1")
|
||||
app.include_router(modules.router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
init_db()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("app.main:app", host="0.0.0.0", port=9000, reload=True)
|
||||
@@ -0,0 +1 @@
|
||||
"""Models package."""
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Association models."""
|
||||
|
||||
from sqlalchemy import Column, Integer, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class UserRole(Base, TimestampMixin):
|
||||
__tablename__ = "user_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="user_roles")
|
||||
role = relationship("Role", back_populates="user_roles")
|
||||
|
||||
|
||||
class ModuleRole(Base, TimestampMixin):
|
||||
__tablename__ = "module_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
module_id = Column(Integer, ForeignKey("modules.id", ondelete="CASCADE"), nullable=False)
|
||||
role_name = Column(String(100), nullable=False)
|
||||
description = Column(Text)
|
||||
|
||||
module = relationship("Module", back_populates="module_roles")
|
||||
user_module_roles = relationship("UserModuleRole", back_populates="module_role", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class UserModuleRole(Base, TimestampMixin):
|
||||
__tablename__ = "user_module_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
module_role_id = Column(Integer, ForeignKey("module_roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="user_module_roles")
|
||||
module_role = relationship("ModuleRole", back_populates="user_module_roles")
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Base model."""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, DateTime, Integer
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Module model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Module(Base, TimestampMixin):
|
||||
__tablename__ = "modules"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
slug = Column(String(50), unique=True, nullable=False)
|
||||
description = Column(Text)
|
||||
url = Column(String(500), nullable=False)
|
||||
icon = Column(String(50), default="Box")
|
||||
is_active = Column(Boolean, default=True)
|
||||
api_key = Column(String(64), unique=True)
|
||||
|
||||
module_roles = relationship("ModuleRole", back_populates="module", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Role model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Role(Base, TimestampMixin):
|
||||
__tablename__ = "roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, nullable=False)
|
||||
description = Column(Text)
|
||||
is_system = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="role", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1,20 @@
|
||||
"""User model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class User(Base, TimestampMixin):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
first_name = Column(String(100), nullable=False)
|
||||
last_name = Column(String(100), nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_superadmin = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="user", cascade="all, delete-orphan")
|
||||
user_module_roles = relationship("UserModuleRole", back_populates="user", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1 @@
|
||||
"""Schemas package."""
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Auth schemas."""
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str = Field(..., min_length=6)
|
||||
first_name: str = Field(..., min_length=1, max_length=100)
|
||||
last_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
user: dict
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
is_active: bool
|
||||
is_superadmin: bool
|
||||
roles: List[str] = []
|
||||
module_roles: Dict[str, List[str]] = {}
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
users: List[UserResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
|
||||
|
||||
class RoleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str]
|
||||
is_system: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RoleCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class ModuleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
slug: str
|
||||
description: Optional[str]
|
||||
url: str
|
||||
icon: str
|
||||
is_active: bool
|
||||
api_key: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ModuleCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
slug: str = Field(..., min_length=1, max_length=50)
|
||||
description: Optional[str] = None
|
||||
url: str
|
||||
icon: str = "Box"
|
||||
|
||||
|
||||
class ModuleRoleResponse(BaseModel):
|
||||
id: int
|
||||
module_id: int
|
||||
role_name: str
|
||||
description: Optional[str]
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Platform settings."""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", case_sensitive=True)
|
||||
|
||||
APP_NAME: str = "Platform"
|
||||
APP_VERSION: str = "1.0.0"
|
||||
APP_DEBUG: bool = True
|
||||
APP_CORS_ORIGINS: str = "http://localhost:5173,http://localhost:5174,http://localhost:8000,http://localhost:8001"
|
||||
|
||||
DATABASE_URL: str = "sqlite:///./platform.db"
|
||||
|
||||
JWT_SECRET_KEY: str = "platform-secret-key-change-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 480
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,10 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
pydantic==2.5.0
|
||||
pydantic-settings==2.1.0
|
||||
python-jose[cryptography]==3.3.0
|
||||
bcrypt==4.0.1
|
||||
httpx==0.25.2
|
||||
python-multipart==0.0.6
|
||||
email-validator==2.1.0
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend-user</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "frontend-user",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"axios": "^1.19.0",
|
||||
"lucide-react": "^1.28.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"oxlint": "^1.75.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext'
|
||||
import Layout from './components/Layout'
|
||||
import Login from './pages/Login'
|
||||
import Register from './pages/Register'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import ModuleView from './pages/ModuleView'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
if (loading) return <div className="flex items-center justify-center h-screen">Загрузка...</div>
|
||||
if (!user) return <Navigate to="/login" />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="module/:slug" element={<ModuleView />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import axios from 'axios'
|
||||
|
||||
const api = axios.create({ baseURL: '/api/v1' })
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
|
||||
api.interceptors.response.use(
|
||||
(r) => r,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('platform_token')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export const authApi = {
|
||||
login: (data: { email: string; password: string }) => api.post('/auth/login', data),
|
||||
register: (data: { email: string; password: string; first_name: string; last_name: string }) => api.post('/auth/register', data),
|
||||
me: () => api.get('/auth/me'),
|
||||
}
|
||||
|
||||
export const modulesApi = {
|
||||
list: () => api.get('/modules'),
|
||||
}
|
||||
|
||||
export default api
|
||||
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,66 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Package, LogOut } from 'lucide-react'
|
||||
|
||||
export default function Layout() {
|
||||
const { user, logout } = useAuth()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
const isModuleView = location.pathname.startsWith('/module/')
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => { logout(); navigate('/login') }
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-100">
|
||||
{/* Top header */}
|
||||
<header className="bg-white shadow-sm flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12 px-4">
|
||||
{/* Left: logo + home */}
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
|
||||
<Link to="/"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Мои модули
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Center: module tabs */}
|
||||
{modules.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
{modules.map(mod => (
|
||||
<Link key={mod.slug} to={`/module/${mod.slug}`}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.slug}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
<Package className="w-3.5 h-3.5" />{mod.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right: logout */}
|
||||
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
|
||||
<LogOut className="w-4 h-4" />Выход
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
|
||||
{isModuleView ? (
|
||||
<Outlet />
|
||||
) : (
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
email: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
is_active: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(res => setUser(res.data))
|
||||
.catch(() => localStorage.removeItem('platform_token'))
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await authApi.login({ email, password })
|
||||
localStorage.setItem('platform_token', res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('platform_token')
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { Package, ExternalLink } from 'lucide-react'
|
||||
|
||||
export default function Dashboard() {
|
||||
const { user } = useAuth()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2">Добро пожаловать, {user?.first_name}!</h1>
|
||||
<p className="text-gray-500 mb-8">Выберите модуль для работы</p>
|
||||
|
||||
{modules.length === 0 ? (
|
||||
<div className="bg-white rounded-lg shadow p-8 text-center">
|
||||
<Package className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<p className="text-gray-500">Нет доступных модулей</p>
|
||||
<p className="text-sm text-gray-400 mt-1">Обратитесь к администратору для подключения модулей</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{modules.map(mod => {
|
||||
const userRoles = user?.module_roles?.[mod.slug] || []
|
||||
return (
|
||||
<Link key={mod.slug} to={`/module/${mod.slug}`}
|
||||
className="bg-white rounded-lg shadow hover:shadow-md transition-shadow p-6 group">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<Package className="w-6 h-6 text-blue-600" />
|
||||
</div>
|
||||
<ExternalLink className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg text-gray-900 mb-1">{mod.name}</h3>
|
||||
<p className="text-sm text-gray-500 mb-3">{mod.description || 'Без описания'}</p>
|
||||
{userRoles.length > 0 && (
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
{userRoles.map((r: string) => (
|
||||
<span key={r} className="px-2 py-0.5 text-xs bg-green-100 text-green-800 rounded-full">{r}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{userRoles.length === 0 && (
|
||||
<span className="text-xs text-gray-400">Нет ролей в модуле</span>
|
||||
)}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await login(email, password)
|
||||
navigate('/')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка входа')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Войдите в аккаунт</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Нет аккаунта? <Link to="/register" className="text-blue-600 hover:underline">Регистрация</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function ModuleView() {
|
||||
const { slug } = useParams()
|
||||
const [module, setModule] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [iframeLoading, setIframeLoading] = useState(true)
|
||||
const [moduleUrl, setModuleUrl] = useState('')
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => {
|
||||
const found = res.data.find((m: any) => m.slug === slug)
|
||||
setModule(found)
|
||||
}).finally(() => setLoading(false))
|
||||
}, [slug])
|
||||
|
||||
useEffect(() => {
|
||||
if (!module) return
|
||||
|
||||
const getToken = () => localStorage.getItem('platform_token') || ''
|
||||
|
||||
const updateUrl = () => {
|
||||
const token = getToken()
|
||||
const url = `${module.url}?token=${encodeURIComponent(token)}`
|
||||
setModuleUrl(url)
|
||||
}
|
||||
|
||||
const sendTokenToIframe = () => {
|
||||
const token = getToken()
|
||||
const iframe = iframeRef.current
|
||||
if (iframe?.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{ type: 'PLATFORM_TOKEN_UPDATE', token },
|
||||
module.url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
updateUrl()
|
||||
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === 'platform_token') {
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}
|
||||
window.addEventListener('storage', handleStorage)
|
||||
|
||||
let lastToken = getToken()
|
||||
const interval = setInterval(() => {
|
||||
const currentToken = getToken()
|
||||
if (currentToken !== lastToken) {
|
||||
lastToken = currentToken
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}, 10000)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [module])
|
||||
|
||||
useEffect(() => {
|
||||
setIframeLoading(true)
|
||||
}, [slug])
|
||||
|
||||
if (loading) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!module) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-gray-500">Модуль не найден</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full">
|
||||
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
|
||||
<h1 className="text-lg font-semibold text-gray-900">{module.name}</h1>
|
||||
<a href={moduleUrl} target="_blank" rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800">
|
||||
<ExternalLink className="w-4 h-4" />Открыть отдельно
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex-1 relative">
|
||||
{iframeLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 z-10">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-2" />
|
||||
<p className="text-sm text-gray-500">Загрузка модуля...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{moduleUrl && (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={moduleUrl}
|
||||
className="w-full h-full border-0"
|
||||
title={module.name}
|
||||
onLoad={() => setIframeLoading(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
export default function Register() {
|
||||
const [form, setForm] = useState({ email: '', password: '', first_name: '', last_name: '' })
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await authApi.register(form)
|
||||
navigate('/login')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка регистрации')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Регистрация</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required minLength={6} />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Уже есть аккаунт? <Link to="/login" className="text-blue-600 hover:underline">Войти</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 5175,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8001',
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"axios": "^1.19.0",
|
||||
"lucide-react": "^1.28.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"oxlint": "^1.75.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext'
|
||||
import Layout from './components/Layout'
|
||||
import Login from './pages/Login'
|
||||
import Register from './pages/Register'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import Users from './pages/Users'
|
||||
import Roles from './pages/Roles'
|
||||
import Modules from './pages/Modules'
|
||||
import ModuleView from './pages/ModuleView'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
if (loading) return <div className="flex items-center justify-center h-screen">Загрузка...</div>
|
||||
if (!user) return <Navigate to="/login" />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="roles" element={<Roles />} />
|
||||
<Route path="modules" element={<Modules />} />
|
||||
<Route path="module/:slug" element={<ModuleView />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import axios from 'axios'
|
||||
|
||||
const api = axios.create({ baseURL: '/api/v1' })
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
api.interceptors.response.use(
|
||||
(r) => r,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('platform_token')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export const authApi = {
|
||||
login: (data: { email: string; password: string }) => api.post('/auth/login', data),
|
||||
register: (data: { email: string; password: string; first_name: string; last_name: string }) => api.post('/auth/register', data),
|
||||
me: () => api.get('/auth/me'),
|
||||
}
|
||||
|
||||
export const usersApi = {
|
||||
list: (params?: { page?: number; page_size?: number; search?: string }) => api.get('/users', { params }),
|
||||
get: (id: number) => api.get(`/users/${id}`),
|
||||
create: (data: { email: string; password: string; first_name: string; last_name: string; is_superadmin?: boolean; role_ids?: number[] }) => api.post('/users', data),
|
||||
update: (id: number, data: { email?: string; first_name?: string; last_name?: string; is_active?: boolean; is_superadmin?: boolean; password?: string }) => api.put(`/users/${id}`, data),
|
||||
delete: (id: number) => api.delete(`/users/${id}`),
|
||||
assignRole: (userId: number, roleId: number) => api.post(`/users/${userId}/roles/${roleId}`),
|
||||
removeRole: (userId: number, roleId: number) => api.delete(`/users/${userId}/roles/${roleId}`),
|
||||
assignModuleRole: (userId: number, moduleRoleId: number) => api.post(`/users/${userId}/module-roles/${moduleRoleId}`),
|
||||
removeModuleRole: (userId: number, moduleRoleId: number) => api.delete(`/users/${userId}/module-roles/${moduleRoleId}`),
|
||||
}
|
||||
|
||||
export const rolesApi = {
|
||||
list: () => api.get('/roles'),
|
||||
create: (data: { name: string; description?: string }) => api.post('/roles', data),
|
||||
update: (id: number, data: { name: string; description?: string }) => api.put(`/roles/${id}`, data),
|
||||
delete: (id: number) => api.delete(`/roles/${id}`),
|
||||
}
|
||||
|
||||
export const modulesApi = {
|
||||
list: () => api.get('/modules'),
|
||||
create: (data: { name: string; slug: string; url: string; description?: string; icon?: string }) => api.post('/modules', data),
|
||||
update: (id: number, data: any) => api.put(`/modules/${id}`, data),
|
||||
delete: (id: number) => api.delete(`/modules/${id}`),
|
||||
syncRoles: (id: number) => api.post(`/modules/${id}/sync-roles`),
|
||||
getRoles: (id: number) => api.get(`/modules/${id}/roles`),
|
||||
}
|
||||
|
||||
export default api
|
||||
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,85 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Package, LogOut } from 'lucide-react'
|
||||
|
||||
export default function Layout() {
|
||||
const { user, logout } = useAuth()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
const isAdmin = user?.is_superadmin || user?.roles?.includes('platform_admin')
|
||||
const isModuleView = location.pathname.startsWith('/module/')
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => { logout(); navigate('/login') }
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-100">
|
||||
{/* Top header */}
|
||||
<header className="bg-white shadow-sm flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12 px-4">
|
||||
{/* Left: logo + main nav */}
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
|
||||
<nav className="flex items-center gap-1">
|
||||
<Link to="/"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Панель
|
||||
</Link>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Link to="/users"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/users') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Пользователи
|
||||
</Link>
|
||||
<Link to="/roles"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/roles') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Роли
|
||||
</Link>
|
||||
<Link to="/modules"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/modules') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Модули
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Center: module tabs */}
|
||||
{modules.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
{modules.map(mod => (
|
||||
<Link key={mod.slug} to={`/module/${mod.slug}`}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.slug}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
<Package className="w-3.5 h-3.5" />{mod.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right: logout */}
|
||||
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
|
||||
<LogOut className="w-4 h-4" />Выход
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
|
||||
{isModuleView ? (
|
||||
<Outlet />
|
||||
) : (
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
email: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
is_active: boolean
|
||||
is_superadmin: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(res => setUser(res.data))
|
||||
.catch(() => localStorage.removeItem('platform_token'))
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await authApi.login({ email, password })
|
||||
localStorage.setItem('platform_token', res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('platform_token')
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { usersApi, rolesApi, modulesApi } from '../api/client'
|
||||
import { Users, Key, Package } from 'lucide-react'
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState({ users: 0, roles: 0, modules: 0 })
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
usersApi.list({ page_size: 1 }).catch(() => ({ data: { total: 0 } })),
|
||||
rolesApi.list().catch(() => ({ data: [] })),
|
||||
modulesApi.list().catch(() => ({ data: [] })),
|
||||
]).then(([u, r, m]) => {
|
||||
setStats({ users: u.data.total, roles: r.data.length, modules: m.data.length })
|
||||
})
|
||||
}, [])
|
||||
|
||||
const cards = [
|
||||
{ name: 'Пользователи', value: stats.users, icon: Users, color: 'bg-blue-500' },
|
||||
{ name: 'Роли', value: stats.roles, icon: Key, color: 'bg-green-500' },
|
||||
{ name: 'Модули', value: stats.modules, icon: Package, color: 'bg-purple-500' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-6">Панель управления</h1>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{cards.map(card => (
|
||||
<div key={card.name} className="bg-white rounded-lg shadow p-6 flex items-center gap-4">
|
||||
<div className={`${card.color} p-3 rounded-lg`}>
|
||||
<card.icon className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">{card.name}</p>
|
||||
<p className="text-2xl font-bold text-gray-900">{card.value}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { user, login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
|
||||
// If already logged in, redirect to home
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
navigate('/')
|
||||
}
|
||||
}, [user, navigate])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await login(email, password)
|
||||
navigate('/')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка входа')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Войдите в аккаунт</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Нет аккаунта? <Link to="/register" className="text-blue-600 hover:underline">Регистрация</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function ModuleView() {
|
||||
const { slug } = useParams()
|
||||
const [module, setModule] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [iframeLoading, setIframeLoading] = useState(true)
|
||||
const [moduleUrl, setModuleUrl] = useState('')
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => {
|
||||
const found = res.data.find((m: any) => m.slug === slug)
|
||||
setModule(found)
|
||||
}).finally(() => setLoading(false))
|
||||
}, [slug])
|
||||
|
||||
// Update iframe URL and send token to iframe
|
||||
useEffect(() => {
|
||||
if (!module) return
|
||||
|
||||
const getToken = () => localStorage.getItem('platform_token') || ''
|
||||
|
||||
const updateUrl = () => {
|
||||
const token = getToken()
|
||||
const url = `${module.url}?token=${encodeURIComponent(token)}`
|
||||
setModuleUrl(url)
|
||||
}
|
||||
|
||||
const sendTokenToIframe = () => {
|
||||
const token = getToken()
|
||||
const iframe = iframeRef.current
|
||||
if (iframe?.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{ type: 'PLATFORM_TOKEN_UPDATE', token },
|
||||
module.url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
updateUrl()
|
||||
|
||||
// Listen for storage changes (token refresh in another tab)
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === 'platform_token') {
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}
|
||||
window.addEventListener('storage', handleStorage)
|
||||
|
||||
// Check periodically for token changes
|
||||
let lastToken = getToken()
|
||||
const interval = setInterval(() => {
|
||||
const currentToken = getToken()
|
||||
if (currentToken !== lastToken) {
|
||||
lastToken = currentToken
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}, 10000)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [module])
|
||||
|
||||
useEffect(() => {
|
||||
setIframeLoading(true)
|
||||
}, [slug])
|
||||
|
||||
if (loading) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!module) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-gray-500">Модуль не найден</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full">
|
||||
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
|
||||
<h1 className="text-lg font-semibold text-gray-900">{module.name}</h1>
|
||||
<a href={moduleUrl} target="_blank" rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800">
|
||||
<ExternalLink className="w-4 h-4" />Открыть отдельно
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex-1 relative">
|
||||
{iframeLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 z-10">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-2" />
|
||||
<p className="text-sm text-gray-500">Загрузка модуля...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{moduleUrl && (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={moduleUrl}
|
||||
className="w-full h-full border-0"
|
||||
title={module.name}
|
||||
onLoad={() => setIframeLoading(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Plus, RefreshCw, Trash2, ExternalLink, Key } from 'lucide-react'
|
||||
|
||||
export default function Modules() {
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', slug: '', url: '', description: '', icon: 'Package' })
|
||||
const [error, setError] = useState('')
|
||||
const [syncResult, setSyncResult] = useState('')
|
||||
const [expandedRoles, setExpandedRoles] = useState<number | null>(null)
|
||||
const [moduleRoles, setModuleRoles] = useState<any[]>([])
|
||||
|
||||
const fetchModules = () => { modulesApi.list().then(res => setModules(res.data)).catch(() => {}) }
|
||||
useEffect(() => { fetchModules() }, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
try {
|
||||
const res = await modulesApi.create(form)
|
||||
setForm({ name: '', slug: '', url: '', description: '', icon: 'Package' })
|
||||
setShowForm(false)
|
||||
fetchModules()
|
||||
alert(`Модуль создан. API Key: ${res.data.api_key}\nСохраните его — он нужен для настройки модуля.`)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка')
|
||||
}
|
||||
}
|
||||
|
||||
const handleSync = async (id: number) => {
|
||||
setSyncResult('')
|
||||
try {
|
||||
const res = await modulesApi.syncRoles(id)
|
||||
setSyncResult(`Импортировано: ${res.data.message}`)
|
||||
fetchModules()
|
||||
} catch (err: any) {
|
||||
setSyncResult(`Ошибка: ${err.response?.data?.detail || err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Отключить модуль?')) return
|
||||
await modulesApi.delete(id)
|
||||
fetchModules()
|
||||
}
|
||||
|
||||
const toggleRoles = async (moduleId: number) => {
|
||||
if (expandedRoles === moduleId) {
|
||||
setExpandedRoles(null)
|
||||
setModuleRoles([])
|
||||
} else {
|
||||
setExpandedRoles(moduleId)
|
||||
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Модули</h1>
|
||||
<button onClick={() => setShowForm(!showForm)} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />Подключить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<form onSubmit={handleCreate} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Название</label>
|
||||
<input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required placeholder="Service Desk"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Slug</label>
|
||||
<input type="text" value={form.slug} onChange={e => setForm({...form, slug: e.target.value})} required placeholder="service-desk"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">URL</label>
|
||||
<input type="text" value={form.url} onChange={e => setForm({...form, url: e.target.value})} required placeholder="http://localhost:8000"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Описание</label>
|
||||
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Подключить</button>
|
||||
<button type="button" onClick={() => setShowForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{syncResult && <div className="bg-blue-50 text-blue-800 p-3 rounded-lg mb-4 text-sm">{syncResult}</div>}
|
||||
|
||||
<div className="space-y-4">
|
||||
{modules.map(mod => (
|
||||
<div key={mod.id} className="bg-white rounded-lg shadow p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold text-lg">{mod.name}</h3>
|
||||
<p className="text-sm text-gray-500">{mod.description}</p>
|
||||
<p className="text-xs text-gray-400 mt-1">{mod.url} · slug: {mod.slug} · ролей: {mod.roles_count}</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => toggleRoles(mod.id)} className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50" title="Роли">
|
||||
<Key className="w-4 h-4" />Роли
|
||||
</button>
|
||||
<button onClick={() => handleSync(mod.id)} className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50" title="Синхронизировать роли">
|
||||
<RefreshCw className="w-4 h-4" />Синхронизировать
|
||||
</button>
|
||||
<a href={mod.url} target="_blank" rel="noopener" className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50">
|
||||
<ExternalLink className="w-4 h-4" />Открыть
|
||||
</a>
|
||||
<button onClick={() => handleDelete(mod.id)} className="flex items-center px-3 py-2 text-sm border rounded-lg hover:bg-red-50 text-red-600">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expandedRoles === mod.id && (
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<h4 className="text-sm font-semibold mb-2">Роли модуля</h4>
|
||||
{moduleRoles.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">Нет ролей. Нажмите "Синхронизировать".</p>
|
||||
) : (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{moduleRoles.map(mr => (
|
||||
<span key={mr.id} className="px-3 py-1 text-sm bg-purple-100 text-purple-800 rounded-full">{mr.role_name}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
export default function Register() {
|
||||
const [form, setForm] = useState({ email: '', password: '', first_name: '', last_name: '' })
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await authApi.register(form)
|
||||
navigate('/login')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка регистрации')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Регистрация</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required minLength={6} />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Уже есть аккаунт? <Link to="/login" className="text-blue-600 hover:underline">Войти</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { rolesApi } from '../api/client'
|
||||
import { Plus, Trash2, Lock } from 'lucide-react'
|
||||
|
||||
export default function Roles() {
|
||||
const [roles, setRoles] = useState<any[]>([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', description: '' })
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const fetchRoles = () => { rolesApi.list().then(res => setRoles(res.data)).catch(() => {}) }
|
||||
useEffect(() => { fetchRoles() }, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
try {
|
||||
await rolesApi.create(form)
|
||||
setForm({ name: '', description: '' })
|
||||
setShowForm(false)
|
||||
fetchRoles()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number, isSystem: boolean) => {
|
||||
if (isSystem) return
|
||||
if (!confirm('Удалить роль?')) return
|
||||
await rolesApi.delete(id)
|
||||
fetchRoles()
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Глобальные роли</h1>
|
||||
<button onClick={() => setShowForm(!showForm)} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />Добавить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<form onSubmit={handleCreate} className="flex gap-4 items-end">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required
|
||||
className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Описание</label>
|
||||
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
|
||||
</form>
|
||||
{error && <p className="text-red-500 text-sm mt-2">{error}</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Имя</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Описание</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Тип</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200">
|
||||
{roles.map(r => (
|
||||
<tr key={r.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 text-sm font-medium">{r.name}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">{r.description || '-'}</td>
|
||||
<td className="px-6 py-4">
|
||||
{r.is_system ? (
|
||||
<span className="flex items-center gap-1 text-xs text-gray-500"><Lock className="w-3 h-3" /> Системная</span>
|
||||
) : (
|
||||
<span className="text-xs text-blue-600">Пользовательская</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
{!r.is_system && (
|
||||
<button onClick={() => handleDelete(r.id, r.is_system)} className="text-red-500 hover:text-red-700">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { usersApi, rolesApi, modulesApi } from '../api/client'
|
||||
import { Search, Shield, Package, Plus, Edit, Trash2, X } from 'lucide-react'
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<any[]>([])
|
||||
const [roles, setRoles] = useState<any[]>([])
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
const [moduleRoles, setModuleRoles] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(1)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [selectedUser, setSelectedUser] = useState<any>(null)
|
||||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||||
const [showEditForm, setShowEditForm] = useState(false)
|
||||
const [editForm, setEditForm] = useState({ first_name: '', last_name: '', email: '', password: '', is_active: true, is_superadmin: false })
|
||||
const [createForm, setCreateForm] = useState({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||||
const [error, setError] = useState('')
|
||||
const pageSize = 20
|
||||
|
||||
const fetchUsers = () => {
|
||||
setLoading(true)
|
||||
usersApi.list({ page, page_size: pageSize, search: search || undefined })
|
||||
.then(res => { setUsers(res.data.users); setTotal(res.data.total) })
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
useEffect(() => { fetchUsers() }, [page])
|
||||
useEffect(() => {
|
||||
rolesApi.list().then(res => setRoles(res.data)).catch(() => {})
|
||||
modulesApi.list().then(res => setModules(res.data)).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const loadModuleRoles = (moduleId: number) => {
|
||||
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
|
||||
}
|
||||
|
||||
const handleAssignRole = async (userId: number, roleId: number) => {
|
||||
await usersApi.assignRole(userId, roleId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
const res = await usersApi.get(userId)
|
||||
setSelectedUser(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveRole = async (userId: number, roleId: number) => {
|
||||
await usersApi.removeRole(userId, roleId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
const res = await usersApi.get(userId)
|
||||
setSelectedUser(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAssignModuleRole = async (userId: number, moduleRoleId: number) => {
|
||||
await usersApi.assignModuleRole(userId, moduleRoleId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
const res = await usersApi.get(userId)
|
||||
setSelectedUser(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
try {
|
||||
await usersApi.create(createForm)
|
||||
setCreateForm({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||||
setShowCreateForm(false)
|
||||
fetchUsers()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка создания')
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!selectedUser) return
|
||||
setError('')
|
||||
try {
|
||||
const data: any = { ...editForm }
|
||||
if (!data.password) delete data.password
|
||||
await usersApi.update(selectedUser.id, data)
|
||||
setShowEditForm(false)
|
||||
fetchUsers()
|
||||
const res = await usersApi.get(selectedUser.id)
|
||||
setSelectedUser(res.data)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка обновления')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (userId: number) => {
|
||||
if (!confirm('Удалить пользователя? Это действие нельзя отменить.')) return
|
||||
await usersApi.delete(userId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
setSelectedUser(null)
|
||||
}
|
||||
}
|
||||
|
||||
const openEditForm = (user: any) => {
|
||||
setEditForm({
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
email: user.email,
|
||||
password: '',
|
||||
is_active: user.is_active,
|
||||
is_superadmin: user.is_superadmin,
|
||||
})
|
||||
setShowEditForm(true)
|
||||
setError('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Пользователи</h1>
|
||||
<button onClick={() => { setShowCreateForm(true); setError('') }} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />Добавить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Create form */}
|
||||
{showCreateForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold">Новый пользователь</h3>
|
||||
<button onClick={() => setShowCreateForm(false)}><X className="w-5 h-5 text-gray-400" /></button>
|
||||
</div>
|
||||
<form onSubmit={handleCreate} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={createForm.first_name} onChange={e => setCreateForm({...createForm, first_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={createForm.last_name} onChange={e => setCreateForm({...createForm, last_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={createForm.email} onChange={e => setCreateForm({...createForm, email: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={createForm.password} onChange={e => setCreateForm({...createForm, password: e.target.value})} required minLength={6}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={createForm.is_superadmin} onChange={e => setCreateForm({...createForm, is_superadmin: e.target.checked})} className="rounded" />
|
||||
<span className="text-sm text-gray-700">Суперадминистратор</span>
|
||||
</label>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
|
||||
<button type="button" onClick={() => setShowCreateForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit form */}
|
||||
{showEditForm && selectedUser && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold">Редактирование: {selectedUser.first_name} {selectedUser.last_name}</h3>
|
||||
<button onClick={() => setShowEditForm(false)}><X className="w-5 h-5 text-gray-400" /></button>
|
||||
</div>
|
||||
<form onSubmit={handleEdit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={editForm.first_name} onChange={e => setEditForm({...editForm, first_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={editForm.last_name} onChange={e => setEditForm({...editForm, last_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={editForm.email} onChange={e => setEditForm({...editForm, email: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Новый пароль (оставьте пустым, чтобы не менять)</label>
|
||||
<input type="password" value={editForm.password} onChange={e => setEditForm({...editForm, password: e.target.value})} minLength={6}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={editForm.is_active} onChange={e => setEditForm({...editForm, is_active: e.target.checked})} className="rounded" />
|
||||
<span className="text-sm text-gray-700">Активен</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={editForm.is_superadmin} onChange={e => setEditForm({...editForm, is_superadmin: e.target.checked})} className="rounded" />
|
||||
<span className="text-sm text-gray-700">Суперадминистратор</span>
|
||||
</label>
|
||||
</div>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Сохранить</button>
|
||||
<button type="button" onClick={() => setShowEditForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<form onSubmit={e => { e.preventDefault(); setPage(1); fetchUsers() }} className="flex gap-4">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute left-3 top-2.5 w-4 h-4 text-gray-400" />
|
||||
<input type="text" value={search} onChange={e => setSearch(e.target.value)} placeholder="Поиск..."
|
||||
className="w-full pl-10 pr-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Найти</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 bg-white rounded-lg shadow overflow-hidden">
|
||||
{loading ? <div className="p-8 text-center">Загрузка...</div> : (
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Пользователь</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Роли</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Статус</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200">
|
||||
{users.map(u => (
|
||||
<tr key={u.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => setSelectedUser(u)}>
|
||||
<td className="px-4 py-3">
|
||||
<p className="text-sm font-medium">{u.first_name} {u.last_name}</p>
|
||||
<p className="text-xs text-gray-500">{u.email}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
{u.roles?.map((r: string) => <span key={r} className="px-2 py-0.5 text-xs bg-blue-100 text-blue-800 rounded-full">{r}</span>)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${u.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
|
||||
{u.is_active ? 'Активен' : 'Неактивен'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3" onClick={e => e.stopPropagation()}>
|
||||
<div className="flex gap-1">
|
||||
<button onClick={() => { setSelectedUser(u); openEditForm(u) }} className="p-1 text-blue-500 hover:text-blue-700" title="Редактировать">
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(u.id)} className="p-1 text-red-500 hover:text-red-700" title="Удалить">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{total > pageSize && (
|
||||
<div className="px-4 py-3 border-t flex justify-between">
|
||||
<button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1} className="px-3 py-1 border rounded disabled:opacity-50">Назад</button>
|
||||
<span className="text-sm text-gray-500">Страница {page}</span>
|
||||
<button onClick={() => setPage(p => p + 1)} disabled={page * pageSize >= total} className="px-3 py-1 border rounded disabled:opacity-50">Далее</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedUser && !showEditForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="font-semibold text-lg">{selectedUser.first_name} {selectedUser.last_name}</h3>
|
||||
<button onClick={() => openEditForm(selectedUser)} className="text-blue-500 hover:text-blue-700">
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mb-4">{selectedUser.email}</p>
|
||||
|
||||
<div className="mb-4">
|
||||
<h4 className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-1"><Shield className="w-4 h-4" /> Глобальные роли</h4>
|
||||
<div className="space-y-1">
|
||||
{roles.map(r => {
|
||||
const assigned = selectedUser.roles?.includes(r.name)
|
||||
return (
|
||||
<div key={r.id} className="flex items-center justify-between text-sm">
|
||||
<span>{r.name}</span>
|
||||
{assigned ? (
|
||||
<button onClick={() => handleRemoveRole(selectedUser.id, r.id)} className="text-red-500 hover:text-red-700 text-xs">Убрать</button>
|
||||
) : (
|
||||
<button onClick={() => handleAssignRole(selectedUser.id, r.id)} className="text-blue-500 hover:text-blue-700 text-xs">Назначить</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-1"><Package className="w-4 h-4" /> Роли модулей</h4>
|
||||
{modules.map(mod => (
|
||||
<div key={mod.id} className="mb-2">
|
||||
<p className="text-xs font-medium text-gray-600">{mod.name}</p>
|
||||
<button onClick={() => loadModuleRoles(mod.id)} className="text-xs text-blue-500 hover:text-blue-700">Загрузить роли</button>
|
||||
<div className="mt-1 space-y-1">
|
||||
{moduleRoles.filter(mr => mr.module_id === mod.id).map(mr => {
|
||||
const assigned = selectedUser.module_roles?.[mod.slug]?.includes(mr.role_name)
|
||||
return (
|
||||
<div key={mr.id} className="flex items-center justify-between text-xs pl-2">
|
||||
<span>{mr.role_name}</span>
|
||||
{assigned ? (
|
||||
<button onClick={() => usersApi.removeModuleRole(selectedUser.id, mr.id).then(() => { usersApi.get(selectedUser.id).then(r => setSelectedUser(r.data)); fetchUsers() })} className="text-red-500">Убрать</button>
|
||||
) : (
|
||||
<button onClick={() => handleAssignModuleRole(selectedUser.id, mr.id)} className="text-blue-500">Назначить</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8001',
|
||||
},
|
||||
},
|
||||
})
|
||||