ownapi 1.0.0__tar.gz → 1.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {ownapi-1.0.0 → ownapi-1.0.1}/PKG-INFO +1 -1
- ownapi-1.0.1/core/auth_users.py +485 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/ownapi/cli.py +149 -8
- {ownapi-1.0.0 → ownapi-1.0.1}/ownapi/sdk.py +236 -12
- {ownapi-1.0.0 → ownapi-1.0.1}/ownapi.egg-info/SOURCES.txt +1 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/pyproject.toml +1 -1
- {ownapi-1.0.0 → ownapi-1.0.1}/server.py +199 -3
- {ownapi-1.0.0 → ownapi-1.0.1}/static/index.html +553 -4
- {ownapi-1.0.0 → ownapi-1.0.1}/MANIFEST.in +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/README.md +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/cli.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/compiler.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/api_keys.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/auto_repair.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/base_client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/consent.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/form_automation.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/hitl_queue.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/onboarding.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/core/token_store.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/healer.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/master_mcp.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/ownapi/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/recorder.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/coingecko/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/coingecko/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/coingecko/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/edevlet/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/edevlet/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/edevlet/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/enuygun/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/enuygun/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/enuygun/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/github_trending/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/github_trending/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/github_trending/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/hackernews/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/hackernews/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/hackernews/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/hepsiburada/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/hepsiburada/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/hepsiburada/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/linkedin_jobs/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/linkedin_jobs/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/linkedin_jobs/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/pegasus/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/pegasus/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/pegasus/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/thy/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/thy/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/thy/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/trendyol/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/trendyol/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/trendyol/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/ucak_bileti/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/ucak_bileti/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/wikipedia/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/wikipedia/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/wikipedia/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/yahoo_finance/__init__.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/yahoo_finance/client.py +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/registry/yahoo_finance/schema.json +0 -0
- {ownapi-1.0.0 → ownapi-1.0.1}/setup.cfg +0 -0
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
"""
|
|
2
|
+
OwnAPI / Shadow-API — Real Sign Up & Sign In User Authentication Module.
|
|
3
|
+
|
|
4
|
+
Persists multi-tenant user accounts in `.sessions/users.json` with:
|
|
5
|
+
- `user_id` / `tenant_id`
|
|
6
|
+
- `name`, `email`, `password_hash`, `provider` ('email', 'google', 'github')
|
|
7
|
+
- `session_token` ('tok_ownapi_...')
|
|
8
|
+
- `created_at`, `updated_at`
|
|
9
|
+
|
|
10
|
+
Automatically provisions every new user in `core/api_keys.py` with:
|
|
11
|
+
- `plan = "free"`
|
|
12
|
+
- `credits = 1000`
|
|
13
|
+
- `max_sites = 2`, `active_sites = []`
|
|
14
|
+
- `mode = "local"`
|
|
15
|
+
- `api_key = "sk-ownapi-..."`
|
|
16
|
+
|
|
17
|
+
Preserves full backward compatibility for `tenant_id="default"`.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import hmac
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
import secrets
|
|
27
|
+
import threading
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from core.api_keys import (
|
|
33
|
+
PLAN_CATALOG,
|
|
34
|
+
get_or_create_tenant,
|
|
35
|
+
get_tenant_info,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
39
|
+
DEFAULT_USERS_FILE = PROJECT_ROOT / ".sessions" / "users.json"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _mask_api_key(api_key: str) -> str:
|
|
43
|
+
clean = str(api_key or "").strip()
|
|
44
|
+
if len(clean) <= 16:
|
|
45
|
+
return clean
|
|
46
|
+
return f"{clean[:10]}••••••••••••••••{clean[-6:]}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _utc_now_iso() -> str:
|
|
50
|
+
return datetime.now(timezone.utc).isoformat()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _hash_password(password: str, salt: str | None = None) -> str:
|
|
54
|
+
"""PBKDF2-HMAC-SHA256 ile güvenli şifre özeti üretir."""
|
|
55
|
+
clean_pw = (password or "").encode("utf-8")
|
|
56
|
+
used_salt = salt or secrets.token_hex(12)
|
|
57
|
+
dk = hashlib.pbkdf2_hmac("sha256", clean_pw, used_salt.encode("utf-8"), 60_000)
|
|
58
|
+
return f"{used_salt}${dk.hex()}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _verify_password(password: str, stored_hash: str) -> bool:
|
|
62
|
+
"""Kaydedilmiş `salt$hash` ile şifreyi doğrular."""
|
|
63
|
+
if not stored_hash or "$" not in stored_hash:
|
|
64
|
+
return False
|
|
65
|
+
salt, _ = stored_hash.split("$", 1)
|
|
66
|
+
candidate = _hash_password(password, salt=salt)
|
|
67
|
+
return hmac.compare_digest(candidate, stored_hash)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _generate_session_token() -> str:
|
|
71
|
+
"""`tok_ownapi_` ile başlayan güvenli oturum token'ı üretir."""
|
|
72
|
+
return f"tok_ownapi_{secrets.token_urlsafe(24)}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _slugify_tenant(base_text: str) -> str:
|
|
76
|
+
cleaned = re.sub(r"[^a-zA-Z0-9_]+", "_", (base_text or "").strip().lower()).strip("_")
|
|
77
|
+
if not cleaned:
|
|
78
|
+
cleaned = "user"
|
|
79
|
+
return cleaned[:24]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class UserAuthManager:
|
|
83
|
+
"""
|
|
84
|
+
`.sessions/users.json` üzerinde kullanıcı kayıt, giriş, OAuth hızlı giriş,
|
|
85
|
+
oturum doğrulama ve profil güncelleme işlemlerini yönetir.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, storage_path: str | Path | None = None) -> None:
|
|
89
|
+
self.storage_path = Path(storage_path) if storage_path else DEFAULT_USERS_FILE
|
|
90
|
+
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
self._lock = threading.RLock()
|
|
92
|
+
|
|
93
|
+
def _load_state(self) -> dict[str, Any]:
|
|
94
|
+
if not self.storage_path.exists():
|
|
95
|
+
return {
|
|
96
|
+
"updated_at": _utc_now_iso(),
|
|
97
|
+
"users": {},
|
|
98
|
+
"email_index": {},
|
|
99
|
+
"token_index": {},
|
|
100
|
+
}
|
|
101
|
+
try:
|
|
102
|
+
raw = self.storage_path.read_text(encoding="utf-8").strip()
|
|
103
|
+
if not raw:
|
|
104
|
+
raise ValueError("Empty users.json")
|
|
105
|
+
data = json.loads(raw)
|
|
106
|
+
if not isinstance(data, dict):
|
|
107
|
+
raise ValueError("Invalid users.json root")
|
|
108
|
+
data.setdefault("users", {})
|
|
109
|
+
data.setdefault("email_index", {})
|
|
110
|
+
data.setdefault("token_index", {})
|
|
111
|
+
return data
|
|
112
|
+
except Exception:
|
|
113
|
+
return {
|
|
114
|
+
"updated_at": _utc_now_iso(),
|
|
115
|
+
"users": {},
|
|
116
|
+
"email_index": {},
|
|
117
|
+
"token_index": {},
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
def _save_state(self, state: dict[str, Any]) -> None:
|
|
121
|
+
state["updated_at"] = _utc_now_iso()
|
|
122
|
+
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
self.storage_path.write_text(
|
|
124
|
+
json.dumps(state, ensure_ascii=False, indent=2) + "\n",
|
|
125
|
+
encoding="utf-8",
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def _enrich_with_account(self, user_record: dict[str, Any]) -> dict[str, Any]:
|
|
129
|
+
"""Kullanıcı profilini `core/api_keys.py` üzerindeki kredi/paket/site bilgileriyle birleştirir."""
|
|
130
|
+
tenant_id = str(user_record.get("tenant_id") or user_record.get("user_id") or "default")
|
|
131
|
+
acc = get_or_create_tenant(tenant_id)
|
|
132
|
+
plan_key = str(acc.get("plan", "free"))
|
|
133
|
+
plan_meta = PLAN_CATALOG.get(plan_key, PLAN_CATALOG["free"])
|
|
134
|
+
max_credits = int(acc.get("max_credits", plan_meta["credits"]))
|
|
135
|
+
remaining_credits = int(acc.get("credits", 0))
|
|
136
|
+
used_credits = int(acc.get("used_credits", max(0, max_credits - remaining_credits)))
|
|
137
|
+
max_sites = int(acc.get("max_sites", plan_meta.get("max_sites", 2)))
|
|
138
|
+
active_sites = list(acc.get("active_sites", []))
|
|
139
|
+
api_key = str(acc.get("api_key", ""))
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
"user_id": str(user_record.get("user_id") or tenant_id),
|
|
143
|
+
"tenant_id": tenant_id,
|
|
144
|
+
"name": str(user_record.get("name") or tenant_id),
|
|
145
|
+
"email": str(user_record.get("email") or f"{tenant_id}@ownapi.dev"),
|
|
146
|
+
"provider": str(user_record.get("provider") or "email"),
|
|
147
|
+
"session_token": str(user_record.get("session_token") or ""),
|
|
148
|
+
"created_at": str(user_record.get("created_at") or acc.get("created_at") or _utc_now_iso()),
|
|
149
|
+
"updated_at": str(user_record.get("updated_at") or acc.get("updated_at") or _utc_now_iso()),
|
|
150
|
+
"plan": plan_key,
|
|
151
|
+
"plan_label": plan_meta["label"],
|
|
152
|
+
"price_usd": plan_meta["price_usd"],
|
|
153
|
+
"mode": str(acc.get("mode", "local")),
|
|
154
|
+
"credits": remaining_credits,
|
|
155
|
+
"remaining_credits": remaining_credits,
|
|
156
|
+
"used_credits": used_credits,
|
|
157
|
+
"max_credits": max_credits,
|
|
158
|
+
"max_sites": max_sites,
|
|
159
|
+
"active_sites": active_sites,
|
|
160
|
+
"active_sites_count": len(active_sites),
|
|
161
|
+
"api_key": api_key,
|
|
162
|
+
"masked_api_key": _mask_api_key(api_key),
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
def signup(
|
|
166
|
+
self,
|
|
167
|
+
email: str,
|
|
168
|
+
password: str | None = None,
|
|
169
|
+
name: str | None = None,
|
|
170
|
+
tenant_id: str | None = None,
|
|
171
|
+
provider: str = "email",
|
|
172
|
+
) -> dict[str, Any]:
|
|
173
|
+
"""
|
|
174
|
+
Yeni kullanıcı kaydı oluşturur (veya e-posta zaten kayıtlıysa şifre eşleşirse giriş yapar).
|
|
175
|
+
Otomatik olarak `core/api_keys.py` üzerinde `free` paket, 1.000 kredi ve 2 site limiti tanımlar.
|
|
176
|
+
"""
|
|
177
|
+
clean_email = (email or "").strip().lower()
|
|
178
|
+
if not clean_email or "@" not in clean_email:
|
|
179
|
+
raise ValueError("Geçerli bir e-posta adresi giriniz.")
|
|
180
|
+
|
|
181
|
+
with self._lock:
|
|
182
|
+
state = self._load_state()
|
|
183
|
+
users = state["users"]
|
|
184
|
+
email_index = state["email_index"]
|
|
185
|
+
token_index = state["token_index"]
|
|
186
|
+
|
|
187
|
+
existing_tid = email_index.get(clean_email)
|
|
188
|
+
if existing_tid and existing_tid in users:
|
|
189
|
+
existing_user = users[existing_tid]
|
|
190
|
+
if password and existing_user.get("password_hash"):
|
|
191
|
+
if not _verify_password(password, existing_user["password_hash"]):
|
|
192
|
+
raise ValueError("Bu e-posta adresi zaten kayıtlı ve girilen şifre hatalı.")
|
|
193
|
+
new_tok = _generate_session_token()
|
|
194
|
+
old_tok = existing_user.get("session_token")
|
|
195
|
+
if old_tok and old_tok in token_index:
|
|
196
|
+
token_index.pop(old_tok, None)
|
|
197
|
+
existing_user["session_token"] = new_tok
|
|
198
|
+
if name and name.strip():
|
|
199
|
+
existing_user["name"] = name.strip()
|
|
200
|
+
existing_user["updated_at"] = _utc_now_iso()
|
|
201
|
+
token_index[new_tok] = existing_tid
|
|
202
|
+
self._save_state(state)
|
|
203
|
+
return self._enrich_with_account(existing_user)
|
|
204
|
+
|
|
205
|
+
email_prefix = clean_email.split("@", 1)[0]
|
|
206
|
+
display_name = (name or "").strip() or email_prefix.replace(".", " ").replace("_", " ").title()
|
|
207
|
+
|
|
208
|
+
if tenant_id and tenant_id.strip():
|
|
209
|
+
candidate_tid = _slugify_tenant(tenant_id.strip())
|
|
210
|
+
else:
|
|
211
|
+
base_slug = _slugify_tenant(email_prefix)
|
|
212
|
+
candidate_tid = f"usr_{base_slug}_{secrets.token_hex(3)}"
|
|
213
|
+
|
|
214
|
+
while candidate_tid in users and candidate_tid != "default":
|
|
215
|
+
candidate_tid = f"usr_{_slugify_tenant(email_prefix)}_{secrets.token_hex(3)}"
|
|
216
|
+
|
|
217
|
+
now = _utc_now_iso()
|
|
218
|
+
session_token = _generate_session_token()
|
|
219
|
+
pw_hash = _hash_password(password or secrets.token_hex(8))
|
|
220
|
+
|
|
221
|
+
user_record = {
|
|
222
|
+
"user_id": candidate_tid,
|
|
223
|
+
"tenant_id": candidate_tid,
|
|
224
|
+
"name": display_name,
|
|
225
|
+
"email": clean_email,
|
|
226
|
+
"password_hash": pw_hash,
|
|
227
|
+
"provider": (provider or "email").strip().lower(),
|
|
228
|
+
"session_token": session_token,
|
|
229
|
+
"created_at": now,
|
|
230
|
+
"updated_at": now,
|
|
231
|
+
}
|
|
232
|
+
users[candidate_tid] = user_record
|
|
233
|
+
email_index[clean_email] = candidate_tid
|
|
234
|
+
token_index[session_token] = candidate_tid
|
|
235
|
+
self._save_state(state)
|
|
236
|
+
|
|
237
|
+
# Otomatik olarak core/api_keys.py üzerinde free paket, 1.000 kredi ve 2 site limiti tanımla
|
|
238
|
+
get_or_create_tenant(candidate_tid)
|
|
239
|
+
return self._enrich_with_account(user_record)
|
|
240
|
+
|
|
241
|
+
def login(self, email: str, password: str) -> dict[str, Any]:
|
|
242
|
+
"""E-posta ve şifre ile giriş yapar, yeni `session_token` üretip kullanıcı bilgilerini döndürür."""
|
|
243
|
+
clean_email = (email or "").strip().lower()
|
|
244
|
+
if not clean_email:
|
|
245
|
+
raise ValueError("E-posta adresi zorunludur.")
|
|
246
|
+
|
|
247
|
+
with self._lock:
|
|
248
|
+
state = self._load_state()
|
|
249
|
+
users = state["users"]
|
|
250
|
+
email_index = state["email_index"]
|
|
251
|
+
token_index = state["token_index"]
|
|
252
|
+
|
|
253
|
+
tid = email_index.get(clean_email)
|
|
254
|
+
if not tid or tid not in users:
|
|
255
|
+
raise ValueError("Bu e-posta adresine ait kullanıcı bulunamadı. Lütfen önce kayıt olun.")
|
|
256
|
+
|
|
257
|
+
user_record = users[tid]
|
|
258
|
+
stored_hash = str(user_record.get("password_hash") or "")
|
|
259
|
+
if stored_hash and not _verify_password(password or "", stored_hash):
|
|
260
|
+
raise ValueError("E-posta veya şifre hatalı.")
|
|
261
|
+
|
|
262
|
+
old_tok = user_record.get("session_token")
|
|
263
|
+
if old_tok and old_tok in token_index:
|
|
264
|
+
token_index.pop(old_tok, None)
|
|
265
|
+
|
|
266
|
+
new_tok = _generate_session_token()
|
|
267
|
+
user_record["session_token"] = new_tok
|
|
268
|
+
user_record["updated_at"] = _utc_now_iso()
|
|
269
|
+
token_index[new_tok] = tid
|
|
270
|
+
self._save_state(state)
|
|
271
|
+
|
|
272
|
+
return self._enrich_with_account(user_record)
|
|
273
|
+
|
|
274
|
+
def oauth_quick(
|
|
275
|
+
self,
|
|
276
|
+
provider: str = "google",
|
|
277
|
+
email: str | None = None,
|
|
278
|
+
name: str | None = None,
|
|
279
|
+
tenant_id: str | None = None,
|
|
280
|
+
) -> dict[str, Any]:
|
|
281
|
+
"""
|
|
282
|
+
'Google ile Giriş Yap' / 'GitHub ile Giriş Yap' butonları için sürtünmesiz
|
|
283
|
+
tek tıkla hesap açma veya mevcut hesaba giriş yapma akışı.
|
|
284
|
+
"""
|
|
285
|
+
clean_provider = (provider or "google").strip().lower()
|
|
286
|
+
if clean_provider not in ("google", "github"):
|
|
287
|
+
clean_provider = "google"
|
|
288
|
+
|
|
289
|
+
clean_email = (email or "").strip().lower()
|
|
290
|
+
if not clean_email:
|
|
291
|
+
clean_email = f"{clean_provider}.user@ownapi.dev"
|
|
292
|
+
|
|
293
|
+
default_name = "Google Kullanıcısı" if clean_provider == "google" else "GitHub Geliştiricisi"
|
|
294
|
+
display_name = (name or "").strip() or default_name
|
|
295
|
+
|
|
296
|
+
with self._lock:
|
|
297
|
+
state = self._load_state()
|
|
298
|
+
users = state["users"]
|
|
299
|
+
email_index = state["email_index"]
|
|
300
|
+
token_index = state["token_index"]
|
|
301
|
+
|
|
302
|
+
existing_tid = email_index.get(clean_email)
|
|
303
|
+
if existing_tid and existing_tid in users:
|
|
304
|
+
user_record = users[existing_tid]
|
|
305
|
+
old_tok = user_record.get("session_token")
|
|
306
|
+
if old_tok and old_tok in token_index:
|
|
307
|
+
token_index.pop(old_tok, None)
|
|
308
|
+
new_tok = _generate_session_token()
|
|
309
|
+
user_record["session_token"] = new_tok
|
|
310
|
+
user_record["provider"] = clean_provider
|
|
311
|
+
if name and name.strip():
|
|
312
|
+
user_record["name"] = name.strip()
|
|
313
|
+
user_record["updated_at"] = _utc_now_iso()
|
|
314
|
+
token_index[new_tok] = existing_tid
|
|
315
|
+
self._save_state(state)
|
|
316
|
+
return self._enrich_with_account(user_record)
|
|
317
|
+
|
|
318
|
+
return self.signup(
|
|
319
|
+
email=clean_email,
|
|
320
|
+
password=secrets.token_hex(12),
|
|
321
|
+
name=display_name,
|
|
322
|
+
tenant_id=tenant_id,
|
|
323
|
+
provider=clean_provider,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
def resolve_user(self, identifier: str | None = None) -> dict[str, Any]:
|
|
327
|
+
"""
|
|
328
|
+
`session_token` ('tok_ownapi_...'), `api_key` ('sk-ownapi-...'), `email` veya `tenant_id`
|
|
329
|
+
üzerinden kullanıcıyı bulur. `default` kiracısı için geriye dönük uyumluluğu korur.
|
|
330
|
+
"""
|
|
331
|
+
ident = (identifier or "default").strip() or "default"
|
|
332
|
+
with self._lock:
|
|
333
|
+
state = self._load_state()
|
|
334
|
+
users = state["users"]
|
|
335
|
+
email_index = state["email_index"]
|
|
336
|
+
token_index = state["token_index"]
|
|
337
|
+
|
|
338
|
+
if ident in token_index:
|
|
339
|
+
tid = token_index[ident]
|
|
340
|
+
if tid in users:
|
|
341
|
+
return self._enrich_with_account(users[tid])
|
|
342
|
+
|
|
343
|
+
if ident in users:
|
|
344
|
+
return self._enrich_with_account(users[ident])
|
|
345
|
+
|
|
346
|
+
if ident.lower() in email_index:
|
|
347
|
+
tid = email_index[ident.lower()]
|
|
348
|
+
if tid in users:
|
|
349
|
+
return self._enrich_with_account(users[tid])
|
|
350
|
+
|
|
351
|
+
if ident.startswith("sk-ownapi-"):
|
|
352
|
+
acc = get_tenant_info(ident)
|
|
353
|
+
resolved_tid = str(acc.get("tenant_id") or "default")
|
|
354
|
+
if resolved_tid in users:
|
|
355
|
+
return self._enrich_with_account(users[resolved_tid])
|
|
356
|
+
return self._enrich_with_account({
|
|
357
|
+
"user_id": resolved_tid,
|
|
358
|
+
"tenant_id": resolved_tid,
|
|
359
|
+
"name": "Varsayılan Geliştirici" if resolved_tid == "default" else resolved_tid,
|
|
360
|
+
"email": f"{resolved_tid}@ownapi.dev",
|
|
361
|
+
"provider": "local",
|
|
362
|
+
"session_token": "",
|
|
363
|
+
})
|
|
364
|
+
|
|
365
|
+
# Geriye dönük uyumluluk: 'default' veya doğrudan tenant_id
|
|
366
|
+
return self._enrich_with_account({
|
|
367
|
+
"user_id": ident,
|
|
368
|
+
"tenant_id": ident,
|
|
369
|
+
"name": "Varsayılan Geliştirici" if ident == "default" else ident,
|
|
370
|
+
"email": f"{ident}@ownapi.dev",
|
|
371
|
+
"provider": "local",
|
|
372
|
+
"session_token": "",
|
|
373
|
+
})
|
|
374
|
+
|
|
375
|
+
def update_profile(
|
|
376
|
+
self,
|
|
377
|
+
identifier: str,
|
|
378
|
+
name: str | None = None,
|
|
379
|
+
email: str | None = None,
|
|
380
|
+
password: str | None = None,
|
|
381
|
+
) -> dict[str, Any]:
|
|
382
|
+
"""Kullanıcının ad, e-posta veya şifre bilgilerini günceller."""
|
|
383
|
+
current = self.resolve_user(identifier)
|
|
384
|
+
tid = str(current["tenant_id"])
|
|
385
|
+
|
|
386
|
+
with self._lock:
|
|
387
|
+
state = self._load_state()
|
|
388
|
+
users = state["users"]
|
|
389
|
+
email_index = state["email_index"]
|
|
390
|
+
token_index = state["token_index"]
|
|
391
|
+
|
|
392
|
+
now = _utc_now_iso()
|
|
393
|
+
if tid not in users:
|
|
394
|
+
tok = _generate_session_token()
|
|
395
|
+
users[tid] = {
|
|
396
|
+
"user_id": tid,
|
|
397
|
+
"tenant_id": tid,
|
|
398
|
+
"name": current.get("name") or tid,
|
|
399
|
+
"email": current.get("email") or f"{tid}@ownapi.dev",
|
|
400
|
+
"password_hash": "",
|
|
401
|
+
"provider": current.get("provider") or "email",
|
|
402
|
+
"session_token": tok,
|
|
403
|
+
"created_at": now,
|
|
404
|
+
"updated_at": now,
|
|
405
|
+
}
|
|
406
|
+
email_index[users[tid]["email"].lower()] = tid
|
|
407
|
+
token_index[tok] = tid
|
|
408
|
+
|
|
409
|
+
user_record = users[tid]
|
|
410
|
+
if name is not None and name.strip():
|
|
411
|
+
user_record["name"] = name.strip()
|
|
412
|
+
|
|
413
|
+
if email is not None and email.strip():
|
|
414
|
+
new_email = email.strip().lower()
|
|
415
|
+
if "@" not in new_email:
|
|
416
|
+
raise ValueError("Geçerli bir e-posta adresi giriniz.")
|
|
417
|
+
existing_owner = email_index.get(new_email)
|
|
418
|
+
if existing_owner and existing_owner != tid:
|
|
419
|
+
raise ValueError("Bu e-posta adresi başka bir hesap tarafından kullanılıyor.")
|
|
420
|
+
old_email = str(user_record.get("email") or "").lower()
|
|
421
|
+
if old_email in email_index and email_index[old_email] == tid:
|
|
422
|
+
email_index.pop(old_email, None)
|
|
423
|
+
user_record["email"] = new_email
|
|
424
|
+
email_index[new_email] = tid
|
|
425
|
+
|
|
426
|
+
if password is not None and password.strip():
|
|
427
|
+
user_record["password_hash"] = _hash_password(password.strip())
|
|
428
|
+
|
|
429
|
+
user_record["updated_at"] = now
|
|
430
|
+
self._save_state(state)
|
|
431
|
+
return self._enrich_with_account(user_record)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
_DEFAULT_AUTH_MANAGER = UserAuthManager()
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def signup_user(
|
|
438
|
+
email: str,
|
|
439
|
+
password: str | None = None,
|
|
440
|
+
name: str | None = None,
|
|
441
|
+
tenant_id: str | None = None,
|
|
442
|
+
provider: str = "email",
|
|
443
|
+
storage_path: str | Path | None = None,
|
|
444
|
+
) -> dict[str, Any]:
|
|
445
|
+
mgr = UserAuthManager(storage_path) if storage_path else _DEFAULT_AUTH_MANAGER
|
|
446
|
+
return mgr.signup(email=email, password=password, name=name, tenant_id=tenant_id, provider=provider)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def login_user(
|
|
450
|
+
email: str,
|
|
451
|
+
password: str,
|
|
452
|
+
storage_path: str | Path | None = None,
|
|
453
|
+
) -> dict[str, Any]:
|
|
454
|
+
mgr = UserAuthManager(storage_path) if storage_path else _DEFAULT_AUTH_MANAGER
|
|
455
|
+
return mgr.login(email=email, password=password)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def oauth_quick_user(
|
|
459
|
+
provider: str = "google",
|
|
460
|
+
email: str | None = None,
|
|
461
|
+
name: str | None = None,
|
|
462
|
+
tenant_id: str | None = None,
|
|
463
|
+
storage_path: str | Path | None = None,
|
|
464
|
+
) -> dict[str, Any]:
|
|
465
|
+
mgr = UserAuthManager(storage_path) if storage_path else _DEFAULT_AUTH_MANAGER
|
|
466
|
+
return mgr.oauth_quick(provider=provider, email=email, name=name, tenant_id=tenant_id)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def get_user_profile(
|
|
470
|
+
identifier: str | None = None,
|
|
471
|
+
storage_path: str | Path | None = None,
|
|
472
|
+
) -> dict[str, Any]:
|
|
473
|
+
mgr = UserAuthManager(storage_path) if storage_path else _DEFAULT_AUTH_MANAGER
|
|
474
|
+
return mgr.resolve_user(identifier=identifier)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def update_user_profile(
|
|
478
|
+
identifier: str,
|
|
479
|
+
name: str | None = None,
|
|
480
|
+
email: str | None = None,
|
|
481
|
+
password: str | None = None,
|
|
482
|
+
storage_path: str | Path | None = None,
|
|
483
|
+
) -> dict[str, Any]:
|
|
484
|
+
mgr = UserAuthManager(storage_path) if storage_path else _DEFAULT_AUTH_MANAGER
|
|
485
|
+
return mgr.update_profile(identifier=identifier, name=name, email=email, password=password)
|
|
@@ -24,6 +24,12 @@ if str(PROJECT_ROOT) not in sys.path:
|
|
|
24
24
|
|
|
25
25
|
from cli import app as _root_app
|
|
26
26
|
from core.api_keys import get_or_create_tenant, get_tenant_info, upgrade_plan
|
|
27
|
+
from ownapi.sdk import (
|
|
28
|
+
_remote_http_request,
|
|
29
|
+
get_remote_config_path,
|
|
30
|
+
load_remote_config,
|
|
31
|
+
save_remote_config,
|
|
32
|
+
)
|
|
27
33
|
|
|
28
34
|
console = Console(legacy_windows=False)
|
|
29
35
|
app = _root_app
|
|
@@ -170,6 +176,84 @@ def init_command(
|
|
|
170
176
|
)
|
|
171
177
|
|
|
172
178
|
|
|
179
|
+
@app.command("login")
|
|
180
|
+
def login_command(
|
|
181
|
+
url: str = typer.Option(
|
|
182
|
+
...,
|
|
183
|
+
"--url",
|
|
184
|
+
"-u",
|
|
185
|
+
help="Uzak OwnAPI bulut sunucusu adresi (örn: https://ownapi-production.up.railway.app)",
|
|
186
|
+
),
|
|
187
|
+
key: str = typer.Option(
|
|
188
|
+
...,
|
|
189
|
+
"--key",
|
|
190
|
+
"-k",
|
|
191
|
+
help="Hesabınıza ait sk-ownapi-... gizli API anahtarı",
|
|
192
|
+
),
|
|
193
|
+
tenant_id: str | None = typer.Option(
|
|
194
|
+
None,
|
|
195
|
+
"--tenant",
|
|
196
|
+
"-t",
|
|
197
|
+
help="Opsiyonel kiracı ID'si (belirtilmezse API anahtarından otomatik çözümlenir)",
|
|
198
|
+
),
|
|
199
|
+
config_path: Path | None = typer.Option(
|
|
200
|
+
None,
|
|
201
|
+
"--config",
|
|
202
|
+
"-c",
|
|
203
|
+
help="Özel yapılandırma dosya yolu (varsayılan: ~/.ownapi/config.json)",
|
|
204
|
+
),
|
|
205
|
+
) -> None:
|
|
206
|
+
"""
|
|
207
|
+
Farklı bir bilgisayardan uzak OwnAPI bulut sunucusuna bağlanmak için
|
|
208
|
+
sunucu URL'sini ve `sk-ownapi-...` anahtarını `~/.ownapi/config.json` içine kaydeder.
|
|
209
|
+
"""
|
|
210
|
+
saved_path = save_remote_config(
|
|
211
|
+
url=url,
|
|
212
|
+
api_key=key,
|
|
213
|
+
tenant_id=tenant_id,
|
|
214
|
+
config_path=config_path,
|
|
215
|
+
)
|
|
216
|
+
cfg = load_remote_config(saved_path)
|
|
217
|
+
clean_url = cfg.get("url", url)
|
|
218
|
+
clean_key = cfg.get("api_key", key)
|
|
219
|
+
|
|
220
|
+
remote_status_line = "[dim]Çevrimdışı kaydedildi (ilk çağrıda doğrulanacak)[/dim]"
|
|
221
|
+
try:
|
|
222
|
+
acc = _remote_http_request(
|
|
223
|
+
server_url=clean_url,
|
|
224
|
+
path="/api/v1/account",
|
|
225
|
+
method="GET",
|
|
226
|
+
api_key=clean_key,
|
|
227
|
+
timeout=10.0,
|
|
228
|
+
)
|
|
229
|
+
resolved_tid = acc.get("tenant_id")
|
|
230
|
+
if resolved_tid and resolved_tid != cfg.get("tenant_id"):
|
|
231
|
+
save_remote_config(url=clean_url, api_key=clean_key, tenant_id=str(resolved_tid), config_path=saved_path)
|
|
232
|
+
rem_c = format_tr_number(acc.get("remaining_credits", acc.get("credits", 0)))
|
|
233
|
+
max_s = acc.get("max_sites", 2)
|
|
234
|
+
act_s = acc.get("active_sites_count", len(acc.get("active_sites", [])))
|
|
235
|
+
remote_status_line = (
|
|
236
|
+
f"[bold green]✔ Bağlantı Doğrulandı[/bold green] — "
|
|
237
|
+
f"Kiracı: [white]{resolved_tid}[/white] | Paket: [magenta]{acc.get('plan')}[/magenta] | "
|
|
238
|
+
f"Kredi: [green]{rem_c}[/green] | Siteler: [cyan]{act_s}/{max_s}[/cyan]"
|
|
239
|
+
)
|
|
240
|
+
except Exception as exc:
|
|
241
|
+
remote_status_line = f"[yellow]⚠ Kaydedildi ({exc})[/yellow]"
|
|
242
|
+
|
|
243
|
+
out_console = Console(file=sys.stdout, legacy_windows=False)
|
|
244
|
+
out_console.print(
|
|
245
|
+
Panel.fit(
|
|
246
|
+
f"[bold green]✔ OwnAPI Uzak Bulut Sunucusu Bağlantısı Kaydedildi![/bold green]\n\n"
|
|
247
|
+
f"[bold cyan]🌍 Uzak Sunucu URL:[/bold cyan] [bold underline white]{clean_url}[/bold underline white]\n"
|
|
248
|
+
f"[bold cyan]🔑 API Anahtarı:[/bold cyan] [bold yellow]{clean_key}[/bold yellow]\n"
|
|
249
|
+
f"[bold cyan]📂 Kayıt Dosyası:[/bold cyan] [underline]{saved_path}[/underline]\n"
|
|
250
|
+
f"[bold cyan]📡 Sunucu Durumu:[/bold cyan] {remote_status_line}",
|
|
251
|
+
title="🔐 OwnAPI Remote Login (ownapi login)",
|
|
252
|
+
border_style="cyan",
|
|
253
|
+
)
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
173
257
|
@app.command("status")
|
|
174
258
|
def status_command(
|
|
175
259
|
tenant_id_or_key: str = typer.Option(
|
|
@@ -184,34 +268,91 @@ def status_command(
|
|
|
184
268
|
"-u",
|
|
185
269
|
help="İsteğe bağlı paket yükseltme ('starter_cloud' veya 'growth_cloud')",
|
|
186
270
|
),
|
|
271
|
+
url: str | None = typer.Option(
|
|
272
|
+
None,
|
|
273
|
+
"--url",
|
|
274
|
+
help="Opsiyonel uzak sunucu URL'si (belirtilmezse ~/.ownapi/config.json veya OWNAPI_SERVER_URL kontrol edilir)",
|
|
275
|
+
),
|
|
276
|
+
config_path: Path | None = typer.Option(
|
|
277
|
+
None,
|
|
278
|
+
"--config",
|
|
279
|
+
"-c",
|
|
280
|
+
help="Özel ~/.ownapi/config.json dosya yolu",
|
|
281
|
+
),
|
|
187
282
|
) -> None:
|
|
188
283
|
"""
|
|
189
284
|
Kullanıcının kalan kredisini (`1.000` kredi), paketini (`free` / `starter_cloud` / `growth_cloud`),
|
|
190
285
|
çalışma modunu (`local` / `cloud`) ve `sk-ownapi-...` anahtarını terminalde şık bir kutu içinde gösterir.
|
|
286
|
+
Eğer `~/.ownapi/config.json` veya `OWNAPI_SERVER_URL` tanımlıysa doğrudan uzak bulut sunucusundan sorgular.
|
|
191
287
|
"""
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
288
|
+
remote_cfg = load_remote_config(config_path)
|
|
289
|
+
remote_url = (url or os.getenv("OWNAPI_SERVER_URL", "") or str(remote_cfg.get("url") or "")).strip().rstrip("/")
|
|
290
|
+
remote_key = (
|
|
291
|
+
tenant_id_or_key
|
|
292
|
+
if tenant_id_or_key.startswith("sk-ownapi-")
|
|
293
|
+
else (os.getenv("OWNAPI_API_KEY", "").strip() or str(remote_cfg.get("api_key") or "").strip())
|
|
294
|
+
)
|
|
198
295
|
|
|
199
|
-
|
|
200
|
-
|
|
296
|
+
using_remote = False
|
|
297
|
+
if remote_url:
|
|
298
|
+
try:
|
|
299
|
+
if upgrade:
|
|
300
|
+
tenant_record = _remote_http_request(
|
|
301
|
+
server_url=remote_url,
|
|
302
|
+
path="/api/v1/billing/upgrade",
|
|
303
|
+
method="POST",
|
|
304
|
+
api_key=remote_key or None,
|
|
305
|
+
payload={
|
|
306
|
+
"tenant_id": str(remote_cfg.get("tenant_id") or tenant_id_or_key or "default"),
|
|
307
|
+
"plan": upgrade,
|
|
308
|
+
},
|
|
309
|
+
)
|
|
310
|
+
else:
|
|
311
|
+
q_tid = str(remote_cfg.get("tenant_id") or tenant_id_or_key or "default")
|
|
312
|
+
tenant_record = _remote_http_request(
|
|
313
|
+
server_url=remote_url,
|
|
314
|
+
path=f"/api/v1/account?tenant_id={q_tid}",
|
|
315
|
+
method="GET",
|
|
316
|
+
api_key=remote_key or None,
|
|
317
|
+
)
|
|
318
|
+
using_remote = True
|
|
319
|
+
except Exception:
|
|
320
|
+
if upgrade:
|
|
321
|
+
info = get_tenant_info(tenant_id_or_key)
|
|
322
|
+
upgrade_plan(info["tenant_id"], plan=upgrade)
|
|
323
|
+
tenant_record = get_tenant_info(info["tenant_id"])
|
|
324
|
+
else:
|
|
325
|
+
tenant_record = get_tenant_info(tenant_id_or_key)
|
|
326
|
+
else:
|
|
327
|
+
if upgrade:
|
|
328
|
+
info = get_tenant_info(tenant_id_or_key)
|
|
329
|
+
upgrade_plan(info["tenant_id"], plan=upgrade)
|
|
330
|
+
tenant_record = get_tenant_info(info["tenant_id"])
|
|
331
|
+
else:
|
|
332
|
+
tenant_record = get_tenant_info(tenant_id_or_key)
|
|
333
|
+
|
|
334
|
+
credits_fmt = format_tr_number(tenant_record.get("remaining_credits", tenant_record.get("credits", 0)))
|
|
335
|
+
consumed_fmt = format_tr_number(tenant_record.get("total_consumed", tenant_record.get("used_credits", 0)))
|
|
201
336
|
plan_name = str(tenant_record.get("plan", "free"))
|
|
202
337
|
plan_label = str(tenant_record.get("plan_label", plan_name))
|
|
203
338
|
mode_name = str(tenant_record.get("mode", "local"))
|
|
204
339
|
api_key = str(tenant_record.get("api_key", ""))
|
|
205
340
|
price_usd = int(tenant_record.get("price_usd", 0))
|
|
341
|
+
max_sites = int(tenant_record.get("max_sites", 2))
|
|
342
|
+
active_sites = tenant_record.get("active_sites", [])
|
|
343
|
+
active_sites_count = int(tenant_record.get("active_sites_count", len(active_sites) if isinstance(active_sites, list) else 0))
|
|
206
344
|
|
|
207
345
|
table = Table(show_header=False, box=None, pad_edge=False)
|
|
208
346
|
table.add_column("Alan", style="bold cyan", width=22)
|
|
209
347
|
table.add_column("Değer", style="white")
|
|
210
348
|
|
|
349
|
+
if using_remote:
|
|
350
|
+
table.add_row("🌍 Uzak Sunucu", f"[bold underline cyan]{remote_url}[/bold underline cyan]")
|
|
211
351
|
table.add_row("👤 Kiracı (Tenant)", f"[bold white]{tenant_record.get('tenant_id', 'default')}[/bold white]")
|
|
212
352
|
table.add_row("📦 Aktif Paket", f"[bold magenta]{plan_name}[/bold magenta] — {plan_label} ([yellow]${price_usd}[/yellow])")
|
|
213
353
|
table.add_row("⚙️ Çalışma Modu", f"[bold green]{mode_name}[/bold green]")
|
|
214
354
|
table.add_row("💳 Kalan Kredi", f"[bold green]{credits_fmt} kredi[/bold green]")
|
|
355
|
+
table.add_row("🌐 Site Limiti", f"[bold cyan]Siteler: {active_sites_count} / {max_sites}[/bold cyan]")
|
|
215
356
|
table.add_row("📊 Harcanan Kredi", f"[dim]{consumed_fmt} kredi[/dim]")
|
|
216
357
|
table.add_row("🔑 API Anahtarı", f"[bold yellow]{api_key}[/bold yellow]")
|
|
217
358
|
|