You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_app.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import json
  18. import re
  19. from datetime import datetime
  20. from flask import request, session, redirect
  21. from werkzeug.security import generate_password_hash, check_password_hash
  22. from flask_login import login_required, current_user, login_user, logout_user
  23. from api.db.db_models import TenantLLM
  24. from api.db.services.llm_service import TenantLLMService, LLMService
  25. from api.utils.api_utils import (
  26. server_error_response,
  27. validate_request,
  28. get_data_error_result,
  29. )
  30. from api.utils import (
  31. get_uuid,
  32. get_format_time,
  33. decrypt,
  34. download_img,
  35. current_timestamp,
  36. datetime_format,
  37. )
  38. from api.db import UserTenantRole, FileType
  39. from api import settings
  40. from api.db.services.user_service import UserService, TenantService, UserTenantService
  41. from api.db.services.file_service import FileService
  42. from api.utils.api_utils import get_json_result, construct_response
  43. @manager.route("/login", methods=["POST", "GET"])
  44. def login():
  45. """
  46. User login endpoint.
  47. ---
  48. tags:
  49. - User
  50. parameters:
  51. - in: body
  52. name: body
  53. description: Login credentials.
  54. required: true
  55. schema:
  56. type: object
  57. properties:
  58. email:
  59. type: string
  60. description: User email.
  61. password:
  62. type: string
  63. description: User password.
  64. responses:
  65. 200:
  66. description: Login successful.
  67. schema:
  68. type: object
  69. 401:
  70. description: Authentication failed.
  71. schema:
  72. type: object
  73. """
  74. if not request.json:
  75. return get_json_result(
  76. data=False, code=settings.RetCode.AUTHENTICATION_ERROR, message="Unauthorized!"
  77. )
  78. email = request.json.get("email", "")
  79. users = UserService.query(email=email)
  80. if not users:
  81. return get_json_result(
  82. data=False,
  83. code=settings.RetCode.AUTHENTICATION_ERROR,
  84. message=f"Email: {email} is not registered!",
  85. )
  86. password = request.json.get("password")
  87. try:
  88. password = decrypt(password)
  89. except BaseException:
  90. return get_json_result(
  91. data=False, code=settings.RetCode.SERVER_ERROR, message="Fail to crypt password"
  92. )
  93. user = UserService.query_user(email, password)
  94. if user:
  95. response_data = user.to_json()
  96. user.access_token = get_uuid()
  97. login_user(user)
  98. user.update_time = (current_timestamp(),)
  99. user.update_date = (datetime_format(datetime.now()),)
  100. user.save()
  101. msg = "Welcome back!"
  102. return construct_response(data=response_data, auth=user.get_id(), message=msg)
  103. else:
  104. return get_json_result(
  105. data=False,
  106. code=settings.RetCode.AUTHENTICATION_ERROR,
  107. message="Email and password do not match!",
  108. )
  109. @manager.route("/github_callback", methods=["GET"])
  110. def github_callback():
  111. """
  112. GitHub OAuth callback endpoint.
  113. ---
  114. tags:
  115. - OAuth
  116. parameters:
  117. - in: query
  118. name: code
  119. type: string
  120. required: true
  121. description: Authorization code from GitHub.
  122. responses:
  123. 200:
  124. description: Authentication successful.
  125. schema:
  126. type: object
  127. """
  128. import requests
  129. res = requests.post(
  130. settings.GITHUB_OAUTH.get("url"),
  131. data={
  132. "client_id": settings.GITHUB_OAUTH.get("client_id"),
  133. "client_secret": settings.GITHUB_OAUTH.get("secret_key"),
  134. "code": request.args.get("code"),
  135. },
  136. headers={"Accept": "application/json"},
  137. )
  138. res = res.json()
  139. if "error" in res:
  140. return redirect("/?error=%s" % res["error_description"])
  141. if "user:email" not in res["scope"].split(","):
  142. return redirect("/?error=user:email not in scope")
  143. session["access_token"] = res["access_token"]
  144. session["access_token_from"] = "github"
  145. user_info = user_info_from_github(session["access_token"])
  146. email_address = user_info["email"]
  147. users = UserService.query(email=email_address)
  148. user_id = get_uuid()
  149. if not users:
  150. # User isn't try to register
  151. try:
  152. try:
  153. avatar = download_img(user_info["avatar_url"])
  154. except Exception as e:
  155. logging.exception(e)
  156. avatar = ""
  157. users = user_register(
  158. user_id,
  159. {
  160. "access_token": session["access_token"],
  161. "email": email_address,
  162. "avatar": avatar,
  163. "nickname": user_info["login"],
  164. "login_channel": "github",
  165. "last_login_time": get_format_time(),
  166. "is_superuser": False,
  167. },
  168. )
  169. if not users:
  170. raise Exception(f"Fail to register {email_address}.")
  171. if len(users) > 1:
  172. raise Exception(f"Same email: {email_address} exists!")
  173. # Try to log in
  174. user = users[0]
  175. login_user(user)
  176. return redirect("/?auth=%s" % user.get_id())
  177. except Exception as e:
  178. rollback_user_registration(user_id)
  179. logging.exception(e)
  180. return redirect("/?error=%s" % str(e))
  181. # User has already registered, try to log in
  182. user = users[0]
  183. user.access_token = get_uuid()
  184. login_user(user)
  185. user.save()
  186. return redirect("/?auth=%s" % user.get_id())
  187. @manager.route("/feishu_callback", methods=["GET"])
  188. def feishu_callback():
  189. """
  190. Feishu OAuth callback endpoint.
  191. ---
  192. tags:
  193. - OAuth
  194. parameters:
  195. - in: query
  196. name: code
  197. type: string
  198. required: true
  199. description: Authorization code from Feishu.
  200. responses:
  201. 200:
  202. description: Authentication successful.
  203. schema:
  204. type: object
  205. """
  206. import requests
  207. app_access_token_res = requests.post(
  208. settings.FEISHU_OAUTH.get("app_access_token_url"),
  209. data=json.dumps(
  210. {
  211. "app_id": settings.FEISHU_OAUTH.get("app_id"),
  212. "app_secret": settings.FEISHU_OAUTH.get("app_secret"),
  213. }
  214. ),
  215. headers={"Content-Type": "application/json; charset=utf-8"},
  216. )
  217. app_access_token_res = app_access_token_res.json()
  218. if app_access_token_res["code"] != 0:
  219. return redirect("/?error=%s" % app_access_token_res)
  220. res = requests.post(
  221. settings.FEISHU_OAUTH.get("user_access_token_url"),
  222. data=json.dumps(
  223. {
  224. "grant_type": settings.FEISHU_OAUTH.get("grant_type"),
  225. "code": request.args.get("code"),
  226. }
  227. ),
  228. headers={
  229. "Content-Type": "application/json; charset=utf-8",
  230. "Authorization": f"Bearer {app_access_token_res['app_access_token']}",
  231. },
  232. )
  233. res = res.json()
  234. if res["code"] != 0:
  235. return redirect("/?error=%s" % res["message"])
  236. if "contact:user.email:readonly" not in res["data"]["scope"].split(" "):
  237. return redirect("/?error=contact:user.email:readonly not in scope")
  238. session["access_token"] = res["data"]["access_token"]
  239. session["access_token_from"] = "feishu"
  240. user_info = user_info_from_feishu(session["access_token"])
  241. email_address = user_info["email"]
  242. users = UserService.query(email=email_address)
  243. user_id = get_uuid()
  244. if not users:
  245. # User isn't try to register
  246. try:
  247. try:
  248. avatar = download_img(user_info["avatar_url"])
  249. except Exception as e:
  250. logging.exception(e)
  251. avatar = ""
  252. users = user_register(
  253. user_id,
  254. {
  255. "access_token": session["access_token"],
  256. "email": email_address,
  257. "avatar": avatar,
  258. "nickname": user_info["en_name"],
  259. "login_channel": "feishu",
  260. "last_login_time": get_format_time(),
  261. "is_superuser": False,
  262. },
  263. )
  264. if not users:
  265. raise Exception(f"Fail to register {email_address}.")
  266. if len(users) > 1:
  267. raise Exception(f"Same email: {email_address} exists!")
  268. # Try to log in
  269. user = users[0]
  270. login_user(user)
  271. return redirect("/?auth=%s" % user.get_id())
  272. except Exception as e:
  273. rollback_user_registration(user_id)
  274. logging.exception(e)
  275. return redirect("/?error=%s" % str(e))
  276. # User has already registered, try to log in
  277. user = users[0]
  278. user.access_token = get_uuid()
  279. login_user(user)
  280. user.save()
  281. return redirect("/?auth=%s" % user.get_id())
  282. def user_info_from_feishu(access_token):
  283. import requests
  284. headers = {
  285. "Content-Type": "application/json; charset=utf-8",
  286. "Authorization": f"Bearer {access_token}",
  287. }
  288. res = requests.get(
  289. "https://open.feishu.cn/open-apis/authen/v1/user_info", headers=headers
  290. )
  291. user_info = res.json()["data"]
  292. user_info["email"] = None if user_info.get("email") == "" else user_info["email"]
  293. return user_info
  294. def user_info_from_github(access_token):
  295. import requests
  296. headers = {"Accept": "application/json", "Authorization": f"token {access_token}"}
  297. res = requests.get(
  298. f"https://api.github.com/user?access_token={access_token}", headers=headers
  299. )
  300. user_info = res.json()
  301. email_info = requests.get(
  302. f"https://api.github.com/user/emails?access_token={access_token}",
  303. headers=headers,
  304. ).json()
  305. user_info["email"] = next(
  306. (email for email in email_info if email["primary"] == True), None
  307. )["email"]
  308. return user_info
  309. @manager.route("/logout", methods=["GET"])
  310. @login_required
  311. def log_out():
  312. """
  313. User logout endpoint.
  314. ---
  315. tags:
  316. - User
  317. security:
  318. - ApiKeyAuth: []
  319. responses:
  320. 200:
  321. description: Logout successful.
  322. schema:
  323. type: object
  324. """
  325. current_user.access_token = ""
  326. current_user.save()
  327. logout_user()
  328. return get_json_result(data=True)
  329. @manager.route("/setting", methods=["POST"])
  330. @login_required
  331. def setting_user():
  332. """
  333. Update user settings.
  334. ---
  335. tags:
  336. - User
  337. security:
  338. - ApiKeyAuth: []
  339. parameters:
  340. - in: body
  341. name: body
  342. description: User settings to update.
  343. required: true
  344. schema:
  345. type: object
  346. properties:
  347. nickname:
  348. type: string
  349. description: New nickname.
  350. email:
  351. type: string
  352. description: New email.
  353. responses:
  354. 200:
  355. description: Settings updated successfully.
  356. schema:
  357. type: object
  358. """
  359. update_dict = {}
  360. request_data = request.json
  361. if request_data.get("password"):
  362. new_password = request_data.get("new_password")
  363. if not check_password_hash(
  364. current_user.password, decrypt(request_data["password"])
  365. ):
  366. return get_json_result(
  367. data=False,
  368. code=settings.RetCode.AUTHENTICATION_ERROR,
  369. message="Password error!",
  370. )
  371. if new_password:
  372. update_dict["password"] = generate_password_hash(decrypt(new_password))
  373. for k in request_data.keys():
  374. if k in [
  375. "password",
  376. "new_password",
  377. "email",
  378. "status",
  379. "is_superuser",
  380. "login_channel",
  381. "is_anonymous",
  382. "is_active",
  383. "is_authenticated",
  384. "last_login_time",
  385. ]:
  386. continue
  387. update_dict[k] = request_data[k]
  388. try:
  389. UserService.update_by_id(current_user.id, update_dict)
  390. return get_json_result(data=True)
  391. except Exception as e:
  392. logging.exception(e)
  393. return get_json_result(
  394. data=False, message="Update failure!", code=settings.RetCode.EXCEPTION_ERROR
  395. )
  396. @manager.route("/info", methods=["GET"])
  397. @login_required
  398. def user_profile():
  399. """
  400. Get user profile information.
  401. ---
  402. tags:
  403. - User
  404. security:
  405. - ApiKeyAuth: []
  406. responses:
  407. 200:
  408. description: User profile retrieved successfully.
  409. schema:
  410. type: object
  411. properties:
  412. id:
  413. type: string
  414. description: User ID.
  415. nickname:
  416. type: string
  417. description: User nickname.
  418. email:
  419. type: string
  420. description: User email.
  421. """
  422. return get_json_result(data=current_user.to_dict())
  423. def rollback_user_registration(user_id):
  424. try:
  425. UserService.delete_by_id(user_id)
  426. except Exception:
  427. pass
  428. try:
  429. TenantService.delete_by_id(user_id)
  430. except Exception:
  431. pass
  432. try:
  433. u = UserTenantService.query(tenant_id=user_id)
  434. if u:
  435. UserTenantService.delete_by_id(u[0].id)
  436. except Exception:
  437. pass
  438. try:
  439. TenantLLM.delete().where(TenantLLM.tenant_id == user_id).execute()
  440. except Exception:
  441. pass
  442. def user_register(user_id, user):
  443. user["id"] = user_id
  444. tenant = {
  445. "id": user_id,
  446. "name": user["nickname"] + "‘s Kingdom",
  447. "llm_id": settings.CHAT_MDL,
  448. "embd_id": settings.EMBEDDING_MDL,
  449. "asr_id": settings.ASR_MDL,
  450. "parser_ids": settings.PARSERS,
  451. "img2txt_id": settings.IMAGE2TEXT_MDL,
  452. "rerank_id": settings.RERANK_MDL,
  453. }
  454. usr_tenant = {
  455. "tenant_id": user_id,
  456. "user_id": user_id,
  457. "invited_by": user_id,
  458. "role": UserTenantRole.OWNER,
  459. }
  460. file_id = get_uuid()
  461. file = {
  462. "id": file_id,
  463. "parent_id": file_id,
  464. "tenant_id": user_id,
  465. "created_by": user_id,
  466. "name": "/",
  467. "type": FileType.FOLDER.value,
  468. "size": 0,
  469. "location": "",
  470. }
  471. tenant_llm = []
  472. for llm in LLMService.query(fid=settings.LLM_FACTORY):
  473. tenant_llm.append(
  474. {
  475. "tenant_id": user_id,
  476. "llm_factory": settings.LLM_FACTORY,
  477. "llm_name": llm.llm_name,
  478. "model_type": llm.model_type,
  479. "api_key": settings.API_KEY,
  480. "api_base": settings.LLM_BASE_URL,
  481. }
  482. )
  483. if not UserService.save(**user):
  484. return
  485. TenantService.insert(**tenant)
  486. UserTenantService.insert(**usr_tenant)
  487. TenantLLMService.insert_many(tenant_llm)
  488. FileService.insert(file)
  489. return UserService.query(email=user["email"])
  490. @manager.route("/register", methods=["POST"])
  491. @validate_request("nickname", "email", "password")
  492. def user_add():
  493. """
  494. Register a new user.
  495. ---
  496. tags:
  497. - User
  498. parameters:
  499. - in: body
  500. name: body
  501. description: Registration details.
  502. required: true
  503. schema:
  504. type: object
  505. properties:
  506. nickname:
  507. type: string
  508. description: User nickname.
  509. email:
  510. type: string
  511. description: User email.
  512. password:
  513. type: string
  514. description: User password.
  515. responses:
  516. 200:
  517. description: Registration successful.
  518. schema:
  519. type: object
  520. """
  521. req = request.json
  522. email_address = req["email"]
  523. # Validate the email address
  524. if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,5}$", email_address):
  525. return get_json_result(
  526. data=False,
  527. message=f"Invalid email address: {email_address}!",
  528. code=settings.RetCode.OPERATING_ERROR,
  529. )
  530. # Check if the email address is already used
  531. if UserService.query(email=email_address):
  532. return get_json_result(
  533. data=False,
  534. message=f"Email: {email_address} has already registered!",
  535. code=settings.RetCode.OPERATING_ERROR,
  536. )
  537. # Construct user info data
  538. nickname = req["nickname"]
  539. user_dict = {
  540. "access_token": get_uuid(),
  541. "email": email_address,
  542. "nickname": nickname,
  543. "password": decrypt(req["password"]),
  544. "login_channel": "password",
  545. "last_login_time": get_format_time(),
  546. "is_superuser": False,
  547. }
  548. user_id = get_uuid()
  549. try:
  550. users = user_register(user_id, user_dict)
  551. if not users:
  552. raise Exception(f"Fail to register {email_address}.")
  553. if len(users) > 1:
  554. raise Exception(f"Same email: {email_address} exists!")
  555. user = users[0]
  556. login_user(user)
  557. return construct_response(
  558. data=user.to_json(),
  559. auth=user.get_id(),
  560. message=f"{nickname}, welcome aboard!",
  561. )
  562. except Exception as e:
  563. rollback_user_registration(user_id)
  564. logging.exception(e)
  565. return get_json_result(
  566. data=False,
  567. message=f"User registration failure, error: {str(e)}",
  568. code=settings.RetCode.EXCEPTION_ERROR,
  569. )
  570. @manager.route("/tenant_info", methods=["GET"])
  571. @login_required
  572. def tenant_info():
  573. """
  574. Get tenant information.
  575. ---
  576. tags:
  577. - Tenant
  578. security:
  579. - ApiKeyAuth: []
  580. responses:
  581. 200:
  582. description: Tenant information retrieved successfully.
  583. schema:
  584. type: object
  585. properties:
  586. tenant_id:
  587. type: string
  588. description: Tenant ID.
  589. name:
  590. type: string
  591. description: Tenant name.
  592. llm_id:
  593. type: string
  594. description: LLM ID.
  595. embd_id:
  596. type: string
  597. description: Embedding model ID.
  598. """
  599. try:
  600. tenants = TenantService.get_info_by(current_user.id)
  601. if not tenants:
  602. return get_data_error_result(message="Tenant not found!")
  603. return get_json_result(data=tenants[0])
  604. except Exception as e:
  605. return server_error_response(e)
  606. @manager.route("/set_tenant_info", methods=["POST"])
  607. @login_required
  608. @validate_request("tenant_id", "asr_id", "embd_id", "img2txt_id", "llm_id")
  609. def set_tenant_info():
  610. """
  611. Update tenant information.
  612. ---
  613. tags:
  614. - Tenant
  615. security:
  616. - ApiKeyAuth: []
  617. parameters:
  618. - in: body
  619. name: body
  620. description: Tenant information to update.
  621. required: true
  622. schema:
  623. type: object
  624. properties:
  625. tenant_id:
  626. type: string
  627. description: Tenant ID.
  628. llm_id:
  629. type: string
  630. description: LLM ID.
  631. embd_id:
  632. type: string
  633. description: Embedding model ID.
  634. asr_id:
  635. type: string
  636. description: ASR model ID.
  637. img2txt_id:
  638. type: string
  639. description: Image to Text model ID.
  640. responses:
  641. 200:
  642. description: Tenant information updated successfully.
  643. schema:
  644. type: object
  645. """
  646. req = request.json
  647. try:
  648. tid = req["tenant_id"]
  649. del req["tenant_id"]
  650. TenantService.update_by_id(tid, req)
  651. return get_json_result(data=True)
  652. except Exception as e:
  653. return server_error_response(e)