lockbot 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lockbot/__init__.py +0 -0
- lockbot/backend/__init__.py +0 -0
- lockbot/backend/app/__init__.py +0 -0
- lockbot/backend/app/admin/__init__.py +0 -0
- lockbot/backend/app/admin/router.py +224 -0
- lockbot/backend/app/auth/__init__.py +0 -0
- lockbot/backend/app/auth/dependencies.py +72 -0
- lockbot/backend/app/auth/models.py +24 -0
- lockbot/backend/app/auth/router.py +140 -0
- lockbot/backend/app/auth/schemas.py +70 -0
- lockbot/backend/app/bots/__init__.py +0 -0
- lockbot/backend/app/bots/encryption.py +57 -0
- lockbot/backend/app/bots/manager.py +106 -0
- lockbot/backend/app/bots/models.py +55 -0
- lockbot/backend/app/bots/router.py +908 -0
- lockbot/backend/app/bots/schemas.py +83 -0
- lockbot/backend/app/bots/webhook_handler.py +70 -0
- lockbot/backend/app/config.py +35 -0
- lockbot/backend/app/database.py +24 -0
- lockbot/backend/app/logs/__init__.py +0 -0
- lockbot/backend/app/main.py +234 -0
- lockbot/core/__init__.py +0 -0
- lockbot/core/base_bot.py +193 -0
- lockbot/core/bot_instance.py +49 -0
- lockbot/core/config.py +325 -0
- lockbot/core/device_bot.py +522 -0
- lockbot/core/device_usage_alert.py +56 -0
- lockbot/core/device_usage_utils.py +187 -0
- lockbot/core/entry.py +81 -0
- lockbot/core/env.py +11 -0
- lockbot/core/handler.py +125 -0
- lockbot/core/i18n/__init__.py +56 -0
- lockbot/core/i18n/en.py +144 -0
- lockbot/core/i18n/zh.py +137 -0
- lockbot/core/io.py +217 -0
- lockbot/core/message_adapter.py +49 -0
- lockbot/core/msg_utils.py +114 -0
- lockbot/core/node_bot.py +387 -0
- lockbot/core/platforms/__init__.py +0 -0
- lockbot/core/platforms/infoflow.py +119 -0
- lockbot/core/queue_bot.py +470 -0
- lockbot/core/request.py +110 -0
- lockbot/core/utils.py +86 -0
- lockbot-2.0.0.dist-info/METADATA +193 -0
- lockbot-2.0.0.dist-info/RECORD +48 -0
- lockbot-2.0.0.dist-info/WHEEL +5 -0
- lockbot-2.0.0.dist-info/licenses/LICENSE +21 -0
- lockbot-2.0.0.dist-info/top_level.txt +1 -0
lockbot/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Admin API routes.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import tempfile
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
|
|
11
|
+
from fastapi import APIRouter, Depends, HTTPException
|
|
12
|
+
from fastapi.responses import FileResponse
|
|
13
|
+
from sqlalchemy.orm import Session
|
|
14
|
+
from starlette.background import BackgroundTask
|
|
15
|
+
|
|
16
|
+
from lockbot.backend.app.auth.dependencies import can_manage_user, require_admin, require_super_admin
|
|
17
|
+
from lockbot.backend.app.auth.models import User
|
|
18
|
+
from lockbot.backend.app.auth.router import _generate_password, _hash_password
|
|
19
|
+
from lockbot.backend.app.auth.schemas import (
|
|
20
|
+
AdminCreateUser,
|
|
21
|
+
AdminEditUser,
|
|
22
|
+
PasswordResetOut,
|
|
23
|
+
UserOut,
|
|
24
|
+
)
|
|
25
|
+
from lockbot.backend.app.bots.models import Bot
|
|
26
|
+
from lockbot.backend.app.database import get_db
|
|
27
|
+
|
|
28
|
+
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
|
29
|
+
|
|
30
|
+
ADMIN_VISIBLE_ROLES = ("admin", "user")
|
|
31
|
+
SUPER_ADMIN_VISIBLE_ROLES = ("super_admin", "admin", "user")
|
|
32
|
+
ADMIN_CREATABLE_ROLES = ("user",)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@router.post("/users", response_model=PasswordResetOut, status_code=201)
|
|
36
|
+
def admin_create_user(
|
|
37
|
+
body: AdminCreateUser,
|
|
38
|
+
operator: User = Depends(require_admin),
|
|
39
|
+
db: Session = Depends(get_db),
|
|
40
|
+
):
|
|
41
|
+
"""Admin creates a user. Super_admin can create admin/user; admin can only create user."""
|
|
42
|
+
# Non-super_admin can only create regular users
|
|
43
|
+
if operator.role != "super_admin" and body.role not in ADMIN_CREATABLE_ROLES:
|
|
44
|
+
raise HTTPException(status_code=403, detail="Cannot create user with this role")
|
|
45
|
+
|
|
46
|
+
if body.role not in SUPER_ADMIN_VISIBLE_ROLES:
|
|
47
|
+
raise HTTPException(status_code=400, detail=f"Invalid role, must be one of {SUPER_ADMIN_VISIBLE_ROLES}")
|
|
48
|
+
|
|
49
|
+
exists = db.query(User).filter(User.username == body.username).first()
|
|
50
|
+
if exists:
|
|
51
|
+
raise HTTPException(status_code=409, detail="Username already taken")
|
|
52
|
+
dup_email = db.query(User).filter(User.email == body.email).first()
|
|
53
|
+
if dup_email:
|
|
54
|
+
raise HTTPException(status_code=409, detail="Email already taken")
|
|
55
|
+
|
|
56
|
+
raw_password = _generate_password()
|
|
57
|
+
user = User(
|
|
58
|
+
username=body.username,
|
|
59
|
+
email=body.email,
|
|
60
|
+
password_hash=_hash_password(raw_password),
|
|
61
|
+
role=body.role,
|
|
62
|
+
max_running_bots=body.max_running_bots,
|
|
63
|
+
must_change_password=True,
|
|
64
|
+
)
|
|
65
|
+
db.add(user)
|
|
66
|
+
db.commit()
|
|
67
|
+
db.refresh(user)
|
|
68
|
+
return PasswordResetOut(id=user.id, username=user.username, new_password=raw_password)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@router.get("/users", response_model=list[UserOut])
|
|
72
|
+
def list_users(
|
|
73
|
+
operator: User = Depends(require_admin),
|
|
74
|
+
db: Session = Depends(get_db),
|
|
75
|
+
):
|
|
76
|
+
"""List users visible to the operator.
|
|
77
|
+
Super_admin sees all; admin sees only users (not admins/super_admins)."""
|
|
78
|
+
if operator.role == "super_admin":
|
|
79
|
+
return db.query(User).all()
|
|
80
|
+
|
|
81
|
+
# admin: see regular users + self
|
|
82
|
+
return db.query(User).filter((User.role == "user") | (User.id == operator.id)).all()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@router.put("/users/{user_id}", response_model=UserOut)
|
|
86
|
+
def admin_edit_user(
|
|
87
|
+
user_id: int,
|
|
88
|
+
body: AdminEditUser,
|
|
89
|
+
operator: User = Depends(require_admin),
|
|
90
|
+
db: Session = Depends(get_db),
|
|
91
|
+
):
|
|
92
|
+
"""Admin edits user profile."""
|
|
93
|
+
target = db.get(User, user_id)
|
|
94
|
+
if not target:
|
|
95
|
+
raise HTTPException(status_code=404, detail="User not found")
|
|
96
|
+
|
|
97
|
+
# Cannot edit users at or above your own level
|
|
98
|
+
if not can_manage_user(operator, target.role):
|
|
99
|
+
raise HTTPException(status_code=403, detail="Cannot manage this user")
|
|
100
|
+
|
|
101
|
+
if body.username is not None and body.username != target.username:
|
|
102
|
+
dup = db.query(User).filter(User.username == body.username).first()
|
|
103
|
+
if dup:
|
|
104
|
+
raise HTTPException(status_code=409, detail="Username already taken")
|
|
105
|
+
target.username = body.username
|
|
106
|
+
|
|
107
|
+
if body.email is not None and body.email != target.email:
|
|
108
|
+
dup = db.query(User).filter(User.email == body.email).first()
|
|
109
|
+
if dup:
|
|
110
|
+
raise HTTPException(status_code=409, detail="Email already taken")
|
|
111
|
+
target.email = body.email
|
|
112
|
+
|
|
113
|
+
if body.role is not None:
|
|
114
|
+
if body.role not in SUPER_ADMIN_VISIBLE_ROLES:
|
|
115
|
+
raise HTTPException(status_code=400, detail="Invalid role")
|
|
116
|
+
# Only super_admin can promote to admin
|
|
117
|
+
if body.role in ("admin", "super_admin") and operator.role != "super_admin":
|
|
118
|
+
raise HTTPException(status_code=403, detail="Only super admin can set this role")
|
|
119
|
+
target.role = body.role
|
|
120
|
+
|
|
121
|
+
if body.max_running_bots is not None:
|
|
122
|
+
target.max_running_bots = body.max_running_bots
|
|
123
|
+
|
|
124
|
+
db.commit()
|
|
125
|
+
db.refresh(target)
|
|
126
|
+
return target
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@router.put("/users/{user_id}/max-bots")
|
|
130
|
+
def set_max_bots(
|
|
131
|
+
user_id: int,
|
|
132
|
+
body: dict,
|
|
133
|
+
operator: User = Depends(require_admin),
|
|
134
|
+
db: Session = Depends(get_db),
|
|
135
|
+
):
|
|
136
|
+
user = db.get(User, user_id)
|
|
137
|
+
if not user:
|
|
138
|
+
raise HTTPException(status_code=404, detail="User not found")
|
|
139
|
+
if not can_manage_user(operator, user.role):
|
|
140
|
+
raise HTTPException(status_code=403, detail="Cannot manage this user")
|
|
141
|
+
user.max_running_bots = body["max_running_bots"]
|
|
142
|
+
db.commit()
|
|
143
|
+
db.refresh(user)
|
|
144
|
+
return {"id": user.id, "max_running_bots": user.max_running_bots}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@router.post("/users/{user_id}/reset-password", response_model=PasswordResetOut)
|
|
148
|
+
def admin_reset_password(
|
|
149
|
+
user_id: int,
|
|
150
|
+
operator: User = Depends(require_admin),
|
|
151
|
+
db: Session = Depends(get_db),
|
|
152
|
+
):
|
|
153
|
+
"""Admin resets a user's password. Returns the new plaintext password."""
|
|
154
|
+
target = db.get(User, user_id)
|
|
155
|
+
if not target:
|
|
156
|
+
raise HTTPException(status_code=404, detail="User not found")
|
|
157
|
+
if not can_manage_user(operator, target.role):
|
|
158
|
+
raise HTTPException(status_code=403, detail="Cannot manage this user")
|
|
159
|
+
raw_password = _generate_password()
|
|
160
|
+
target.password_hash = _hash_password(raw_password)
|
|
161
|
+
target.must_change_password = True
|
|
162
|
+
db.commit()
|
|
163
|
+
db.refresh(target)
|
|
164
|
+
return PasswordResetOut(id=target.id, username=target.username, new_password=raw_password)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@router.get("/bots")
|
|
168
|
+
def list_all_bots(
|
|
169
|
+
_admin: User = Depends(require_admin),
|
|
170
|
+
db: Session = Depends(get_db),
|
|
171
|
+
):
|
|
172
|
+
rows = db.query(Bot, User.username).join(User, Bot.user_id == User.id).all()
|
|
173
|
+
return [
|
|
174
|
+
{c.name: getattr(bot, c.name) for c in bot.__table__.columns} | {"owner": username} for bot, username in rows
|
|
175
|
+
]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@router.get("/stats")
|
|
179
|
+
def platform_stats(
|
|
180
|
+
_admin: User = Depends(require_admin),
|
|
181
|
+
db: Session = Depends(get_db),
|
|
182
|
+
):
|
|
183
|
+
total_users = db.query(User).count()
|
|
184
|
+
bots = db.query(Bot).all()
|
|
185
|
+
return {
|
|
186
|
+
"totalUsers": total_users,
|
|
187
|
+
"totalBots": len(bots),
|
|
188
|
+
"running": sum(1 for b in bots if b.status == "running"),
|
|
189
|
+
"errors": sum(1 for b in bots if b.status == "error"),
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@router.get("/backup")
|
|
194
|
+
def download_backup(
|
|
195
|
+
_admin: User = Depends(require_super_admin),
|
|
196
|
+
):
|
|
197
|
+
"""Download full SQLite database backup (super_admin only)."""
|
|
198
|
+
from lockbot.backend.app.config import DATABASE_URL
|
|
199
|
+
|
|
200
|
+
db_url = DATABASE_URL
|
|
201
|
+
if not db_url.startswith("sqlite:///"):
|
|
202
|
+
raise HTTPException(status_code=400, detail="Backup only supported for SQLite")
|
|
203
|
+
|
|
204
|
+
db_path = db_url[len("sqlite:///") :]
|
|
205
|
+
if not os.path.exists(db_path):
|
|
206
|
+
raise HTTPException(status_code=404, detail="Database file not found")
|
|
207
|
+
|
|
208
|
+
# Copy to temp file to avoid sending a mid-write database
|
|
209
|
+
fd, tmp_path = tempfile.mkstemp(suffix=".db")
|
|
210
|
+
os.close(fd)
|
|
211
|
+
try:
|
|
212
|
+
shutil.copy2(db_path, tmp_path)
|
|
213
|
+
except BaseException:
|
|
214
|
+
with contextlib.suppress(OSError):
|
|
215
|
+
os.unlink(tmp_path)
|
|
216
|
+
raise
|
|
217
|
+
|
|
218
|
+
filename = f"lockbot_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db"
|
|
219
|
+
return FileResponse(
|
|
220
|
+
path=tmp_path,
|
|
221
|
+
filename=filename,
|
|
222
|
+
media_type="application/x-sqlite3",
|
|
223
|
+
background=BackgroundTask(os.unlink, tmp_path),
|
|
224
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""
|
|
2
|
+
JWT authentication dependencies.
|
|
3
|
+
|
|
4
|
+
NOTE: This is a local auth implementation (JWT + local user table).
|
|
5
|
+
To integrate with company SSO / OAuth, replace get_current_user()
|
|
6
|
+
with your SSO token validation logic. All routes use
|
|
7
|
+
Depends(get_current_user), so no other changes are needed.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
|
|
12
|
+
import jwt
|
|
13
|
+
from fastapi import Depends, HTTPException, status
|
|
14
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
15
|
+
from sqlalchemy.orm import Session
|
|
16
|
+
|
|
17
|
+
from lockbot.backend.app.auth.models import User
|
|
18
|
+
from lockbot.backend.app.config import JWT_ALGORITHM, JWT_EXPIRE_MINUTES, JWT_SECRET
|
|
19
|
+
from lockbot.backend.app.database import get_db
|
|
20
|
+
|
|
21
|
+
_security = HTTPBearer(auto_error=False)
|
|
22
|
+
|
|
23
|
+
_ROLE_LEVELS = {"super_admin": 0, "admin": 1, "user": 2}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def create_access_token(user_id: int, must_change_password: bool = False) -> str:
|
|
27
|
+
payload = {
|
|
28
|
+
"sub": str(user_id),
|
|
29
|
+
"exp": datetime.now(timezone.utc) + timedelta(minutes=JWT_EXPIRE_MINUTES),
|
|
30
|
+
"mcp": must_change_password,
|
|
31
|
+
}
|
|
32
|
+
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_current_user(
|
|
36
|
+
credentials: HTTPAuthorizationCredentials | None = Depends(_security),
|
|
37
|
+
db: Session = Depends(get_db),
|
|
38
|
+
) -> User:
|
|
39
|
+
if credentials is None:
|
|
40
|
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
|
41
|
+
token = credentials.credentials
|
|
42
|
+
try:
|
|
43
|
+
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
|
44
|
+
user_id = int(payload["sub"])
|
|
45
|
+
except (jwt.PyJWTError, KeyError, ValueError):
|
|
46
|
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from None
|
|
47
|
+
|
|
48
|
+
user = db.get(User, user_id)
|
|
49
|
+
if user is None:
|
|
50
|
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
51
|
+
return user
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def require_admin(user: User = Depends(get_current_user)) -> User:
|
|
55
|
+
"""Require admin or super_admin."""
|
|
56
|
+
if user.role not in ("admin", "super_admin"):
|
|
57
|
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin required")
|
|
58
|
+
return user
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def require_super_admin(user: User = Depends(get_current_user)) -> User:
|
|
62
|
+
"""Require super_admin only."""
|
|
63
|
+
if user.role != "super_admin":
|
|
64
|
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin required")
|
|
65
|
+
return user
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def can_manage_user(operator: User, target_role: str) -> bool:
|
|
69
|
+
"""Check if operator can manage a user with the given role."""
|
|
70
|
+
op_level = _ROLE_LEVELS.get(operator.role, 3)
|
|
71
|
+
tgt_level = _ROLE_LEVELS.get(target_role, 3)
|
|
72
|
+
return op_level < tgt_level
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
User model
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
from sqlalchemy import Boolean, DateTime, Integer, String, func
|
|
8
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
9
|
+
|
|
10
|
+
from lockbot.backend.app.database import Base
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class User(Base):
|
|
14
|
+
__tablename__ = "users"
|
|
15
|
+
|
|
16
|
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
17
|
+
username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
|
18
|
+
email: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
|
|
19
|
+
password_hash: Mapped[str] = mapped_column(String(256), nullable=False)
|
|
20
|
+
role: Mapped[str] = mapped_column(String(16), nullable=False, default="user")
|
|
21
|
+
max_running_bots: Mapped[int] = mapped_column(Integer, default=10)
|
|
22
|
+
must_change_password: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
|
23
|
+
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
|
24
|
+
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Auth routes: register / login / current user
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
import string
|
|
7
|
+
|
|
8
|
+
import bcrypt as _bcrypt
|
|
9
|
+
from fastapi import APIRouter, Depends, HTTPException, status
|
|
10
|
+
from sqlalchemy import or_
|
|
11
|
+
from sqlalchemy.orm import Session
|
|
12
|
+
|
|
13
|
+
import lockbot.backend.app.config as _config
|
|
14
|
+
from lockbot.backend.app.auth.dependencies import create_access_token, get_current_user
|
|
15
|
+
from lockbot.backend.app.auth.models import User
|
|
16
|
+
from lockbot.backend.app.auth.schemas import (
|
|
17
|
+
ChangeEmail,
|
|
18
|
+
ChangePassword,
|
|
19
|
+
ForceChangePassword,
|
|
20
|
+
TokenOut,
|
|
21
|
+
UserLogin,
|
|
22
|
+
UserOut,
|
|
23
|
+
UserRegister,
|
|
24
|
+
)
|
|
25
|
+
from lockbot.backend.app.database import get_db
|
|
26
|
+
|
|
27
|
+
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _hash_password(password: str) -> str:
|
|
31
|
+
return _bcrypt.hashpw(password.encode(), _bcrypt.gensalt()).decode()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _verify_password(password: str, hashed: str) -> bool:
|
|
35
|
+
return _bcrypt.checkpw(password.encode(), hashed.encode())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _generate_password(length: int = 12) -> str:
|
|
39
|
+
"""Generate a random password with mixed character types."""
|
|
40
|
+
alphabet = string.ascii_letters + string.digits + "!@#$%&*"
|
|
41
|
+
password = [
|
|
42
|
+
secrets.choice(string.ascii_lowercase),
|
|
43
|
+
secrets.choice(string.ascii_uppercase),
|
|
44
|
+
secrets.choice(string.digits),
|
|
45
|
+
secrets.choice("!@#$%&*"),
|
|
46
|
+
]
|
|
47
|
+
password += [secrets.choice(alphabet) for _ in range(length - 4)]
|
|
48
|
+
secrets.SystemRandom().shuffle(password)
|
|
49
|
+
return "".join(password)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@router.post("/register", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
|
53
|
+
def register(body: UserRegister, db: Session = Depends(get_db)):
|
|
54
|
+
if not _config.ALLOW_REGISTER:
|
|
55
|
+
raise HTTPException(status_code=403, detail="Registration is disabled. Contact admin.")
|
|
56
|
+
|
|
57
|
+
exists = db.query(User).filter(or_(User.username == body.username, User.email == body.email)).first()
|
|
58
|
+
if exists:
|
|
59
|
+
raise HTTPException(status_code=409, detail="Username or email already taken")
|
|
60
|
+
|
|
61
|
+
user = User(
|
|
62
|
+
username=body.username,
|
|
63
|
+
email=body.email,
|
|
64
|
+
password_hash=_hash_password(body.password),
|
|
65
|
+
)
|
|
66
|
+
db.add(user)
|
|
67
|
+
db.commit()
|
|
68
|
+
db.refresh(user)
|
|
69
|
+
return user
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@router.post("/login", response_model=TokenOut)
|
|
73
|
+
def login(body: UserLogin, db: Session = Depends(get_db)):
|
|
74
|
+
user = db.query(User).filter(User.username == body.username).first()
|
|
75
|
+
if not user or not _verify_password(body.password, user.password_hash):
|
|
76
|
+
raise HTTPException(status_code=401, detail="Invalid credentials")
|
|
77
|
+
return TokenOut(
|
|
78
|
+
access_token=create_access_token(user.id, user.must_change_password),
|
|
79
|
+
must_change_password=user.must_change_password,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@router.get("/me", response_model=UserOut)
|
|
84
|
+
def me(user: User = Depends(get_current_user)):
|
|
85
|
+
return user
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@router.put("/change-password", response_model=TokenOut)
|
|
89
|
+
def change_password(
|
|
90
|
+
body: ChangePassword,
|
|
91
|
+
user: User = Depends(get_current_user),
|
|
92
|
+
db: Session = Depends(get_db),
|
|
93
|
+
):
|
|
94
|
+
if not _verify_password(body.current_password, user.password_hash):
|
|
95
|
+
raise HTTPException(status_code=400, detail="Current password is incorrect")
|
|
96
|
+
if len(body.new_password) < 6:
|
|
97
|
+
raise HTTPException(status_code=400, detail="Password must be at least 6 characters")
|
|
98
|
+
user.password_hash = _hash_password(body.new_password)
|
|
99
|
+
user.must_change_password = False
|
|
100
|
+
db.commit()
|
|
101
|
+
return TokenOut(
|
|
102
|
+
access_token=create_access_token(user.id, False),
|
|
103
|
+
must_change_password=False,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@router.put("/force-change-password", response_model=TokenOut)
|
|
108
|
+
def force_change_password(
|
|
109
|
+
body: ForceChangePassword,
|
|
110
|
+
user: User = Depends(get_current_user),
|
|
111
|
+
db: Session = Depends(get_db),
|
|
112
|
+
):
|
|
113
|
+
if not user.must_change_password:
|
|
114
|
+
raise HTTPException(status_code=400, detail="No password change required")
|
|
115
|
+
if body.new_password != body.confirm_password:
|
|
116
|
+
raise HTTPException(status_code=400, detail="Passwords do not match")
|
|
117
|
+
if len(body.new_password) < 6:
|
|
118
|
+
raise HTTPException(status_code=400, detail="Password must be at least 6 characters")
|
|
119
|
+
user.password_hash = _hash_password(body.new_password)
|
|
120
|
+
user.must_change_password = False
|
|
121
|
+
db.commit()
|
|
122
|
+
return TokenOut(
|
|
123
|
+
access_token=create_access_token(user.id, False),
|
|
124
|
+
must_change_password=False,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@router.put("/change-email", response_model=UserOut)
|
|
129
|
+
def change_email(
|
|
130
|
+
body: ChangeEmail,
|
|
131
|
+
user: User = Depends(get_current_user),
|
|
132
|
+
db: Session = Depends(get_db),
|
|
133
|
+
):
|
|
134
|
+
exists = db.query(User).filter(User.email == body.new_email).filter(User.id != user.id).first()
|
|
135
|
+
if exists:
|
|
136
|
+
raise HTTPException(status_code=409, detail="Email already taken")
|
|
137
|
+
user.email = body.new_email
|
|
138
|
+
db.commit()
|
|
139
|
+
db.refresh(user)
|
|
140
|
+
return user
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""
|
|
2
|
+
User Pydantic schemas
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class UserRegister(BaseModel):
|
|
11
|
+
username: str
|
|
12
|
+
email: str
|
|
13
|
+
password: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UserLogin(BaseModel):
|
|
17
|
+
username: str
|
|
18
|
+
password: str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UserOut(BaseModel):
|
|
22
|
+
id: int
|
|
23
|
+
username: str
|
|
24
|
+
email: str
|
|
25
|
+
role: str
|
|
26
|
+
max_running_bots: int
|
|
27
|
+
created_at: datetime
|
|
28
|
+
must_change_password: bool = False
|
|
29
|
+
|
|
30
|
+
model_config = {"from_attributes": True}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TokenOut(BaseModel):
|
|
34
|
+
access_token: str
|
|
35
|
+
token_type: str = "bearer"
|
|
36
|
+
must_change_password: bool = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AdminCreateUser(BaseModel):
|
|
40
|
+
username: str
|
|
41
|
+
email: str
|
|
42
|
+
role: str = "user"
|
|
43
|
+
max_running_bots: int = 10
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AdminEditUser(BaseModel):
|
|
47
|
+
username: str | None = None
|
|
48
|
+
email: str | None = None
|
|
49
|
+
role: str | None = None
|
|
50
|
+
max_running_bots: int | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ChangePassword(BaseModel):
|
|
54
|
+
current_password: str
|
|
55
|
+
new_password: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ForceChangePassword(BaseModel):
|
|
59
|
+
new_password: str
|
|
60
|
+
confirm_password: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ChangeEmail(BaseModel):
|
|
64
|
+
new_email: str
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class PasswordResetOut(BaseModel):
|
|
68
|
+
id: int
|
|
69
|
+
username: str
|
|
70
|
+
new_password: str
|
|
File without changes
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sensitive data encryption utilities.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from cryptography.fernet import Fernet
|
|
8
|
+
|
|
9
|
+
from lockbot.backend.app.config import BASE_DIR, ENCRYPTION_KEY
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
_fernet = None
|
|
14
|
+
|
|
15
|
+
# Persistent key file for dev mode (when ENCRYPTION_KEY env var is not set)
|
|
16
|
+
_KEY_FILE = BASE_DIR / "data" / ".encryption_key"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _get_fernet() -> Fernet:
|
|
20
|
+
global _fernet
|
|
21
|
+
if _fernet is None:
|
|
22
|
+
key = ENCRYPTION_KEY
|
|
23
|
+
if not key:
|
|
24
|
+
# Try to load from persistent file first
|
|
25
|
+
if _KEY_FILE.exists():
|
|
26
|
+
key = _KEY_FILE.read_text().strip()
|
|
27
|
+
logger.info("Loaded encryption key from %s", _KEY_FILE)
|
|
28
|
+
else:
|
|
29
|
+
# Auto-generate and persist for dev
|
|
30
|
+
key = Fernet.generate_key().decode()
|
|
31
|
+
_KEY_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
_KEY_FILE.write_text(key)
|
|
33
|
+
logger.warning(
|
|
34
|
+
"Generated new encryption key and saved to %s. Set ENCRYPTION_KEY env var in production.",
|
|
35
|
+
_KEY_FILE,
|
|
36
|
+
)
|
|
37
|
+
_fernet = Fernet(key.encode() if isinstance(key, str) else key)
|
|
38
|
+
return _fernet
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def encrypt(plaintext: str) -> str:
|
|
42
|
+
if not plaintext:
|
|
43
|
+
return ""
|
|
44
|
+
return _get_fernet().encrypt(plaintext.encode()).decode()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def decrypt(ciphertext: str) -> str:
|
|
48
|
+
if not ciphertext:
|
|
49
|
+
return ""
|
|
50
|
+
return _get_fernet().decrypt(ciphertext.encode()).decode()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def mask(value: str, show_last: int = 4) -> str:
|
|
54
|
+
"""Mask display: ***xxxx"""
|
|
55
|
+
if not value or len(value) <= show_last:
|
|
56
|
+
return "***"
|
|
57
|
+
return "***" + value[-show_last:]
|