選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

user_app.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 json
  17. import re
  18. from datetime import datetime
  19. from flask import request, session, redirect
  20. from werkzeug.security import generate_password_hash, check_password_hash
  21. from flask_login import login_required, current_user, login_user, logout_user
  22. from api.db.db_models import TenantLLM
  23. from api.db.services.llm_service import TenantLLMService, LLMService
  24. from api.utils.api_utils import server_error_response, validate_request
  25. from api.utils import get_uuid, get_format_time, decrypt, download_img, current_timestamp, datetime_format
  26. from api.db import UserTenantRole, LLMType, FileType
  27. from api.settings import RetCode, GITHUB_OAUTH, FEISHU_OAUTH, CHAT_MDL, EMBEDDING_MDL, ASR_MDL, IMAGE2TEXT_MDL, PARSERS, \
  28. API_KEY, \
  29. LLM_FACTORY, LLM_BASE_URL, RERANK_MDL
  30. from api.db.services.user_service import UserService, TenantService, UserTenantService
  31. from api.db.services.file_service import FileService
  32. from api.settings import stat_logger
  33. from api.utils.api_utils import get_json_result, construct_response
  34. @manager.route('/login', methods=['POST', 'GET'])
  35. def login():
  36. if not request.json:
  37. return get_json_result(data=False,
  38. retcode=RetCode.AUTHENTICATION_ERROR,
  39. retmsg='Unauthorized!')
  40. email = request.json.get('email', "")
  41. users = UserService.query(email=email)
  42. if not users:
  43. return get_json_result(data=False,
  44. retcode=RetCode.AUTHENTICATION_ERROR,
  45. retmsg=f'Email: {email} is not registered!')
  46. password = request.json.get('password')
  47. try:
  48. password = decrypt(password)
  49. except BaseException:
  50. return get_json_result(data=False,
  51. retcode=RetCode.SERVER_ERROR,
  52. retmsg='Fail to crypt password')
  53. user = UserService.query_user(email, password)
  54. if user:
  55. response_data = user.to_json()
  56. user.access_token = get_uuid()
  57. login_user(user)
  58. user.update_time = current_timestamp(),
  59. user.update_date = datetime_format(datetime.now()),
  60. user.save()
  61. msg = "Welcome back!"
  62. return construct_response(data=response_data, auth=user.get_id(), retmsg=msg)
  63. else:
  64. return get_json_result(data=False,
  65. retcode=RetCode.AUTHENTICATION_ERROR,
  66. retmsg='Email and password do not match!')
  67. @manager.route('/github_callback', methods=['GET'])
  68. def github_callback():
  69. import requests
  70. res = requests.post(GITHUB_OAUTH.get("url"),
  71. data={
  72. "client_id": GITHUB_OAUTH.get("client_id"),
  73. "client_secret": GITHUB_OAUTH.get("secret_key"),
  74. "code": request.args.get('code')},
  75. headers={"Accept": "application/json"})
  76. res = res.json()
  77. if "error" in res:
  78. return redirect("/?error=%s" % res["error_description"])
  79. if "user:email" not in res["scope"].split(","):
  80. return redirect("/?error=user:email not in scope")
  81. session["access_token"] = res["access_token"]
  82. session["access_token_from"] = "github"
  83. user_info = user_info_from_github(session["access_token"])
  84. email_address = user_info["email"]
  85. users = UserService.query(email=email_address)
  86. user_id = get_uuid()
  87. if not users:
  88. # User isn't try to register
  89. try:
  90. try:
  91. avatar = download_img(user_info["avatar_url"])
  92. except Exception as e:
  93. stat_logger.exception(e)
  94. avatar = ""
  95. users = user_register(user_id, {
  96. "access_token": session["access_token"],
  97. "email": email_address,
  98. "avatar": avatar,
  99. "nickname": user_info["login"],
  100. "login_channel": "github",
  101. "last_login_time": get_format_time(),
  102. "is_superuser": False,
  103. })
  104. if not users:
  105. raise Exception(f'Fail to register {email_address}.')
  106. if len(users) > 1:
  107. raise Exception(f'Same email: {email_address} exists!')
  108. # Try to log in
  109. user = users[0]
  110. login_user(user)
  111. return redirect("/?auth=%s" % user.get_id())
  112. except Exception as e:
  113. rollback_user_registration(user_id)
  114. stat_logger.exception(e)
  115. return redirect("/?error=%s" % str(e))
  116. # User has already registered, try to log in
  117. user = users[0]
  118. user.access_token = get_uuid()
  119. login_user(user)
  120. user.save()
  121. return redirect("/?auth=%s" % user.get_id())
  122. @manager.route('/feishu_callback', methods=['GET'])
  123. def feishu_callback():
  124. import requests
  125. app_access_token_res = requests.post(FEISHU_OAUTH.get("app_access_token_url"),
  126. data=json.dumps({
  127. "app_id": FEISHU_OAUTH.get("app_id"),
  128. "app_secret": FEISHU_OAUTH.get("app_secret")
  129. }),
  130. headers={"Content-Type": "application/json; charset=utf-8"})
  131. app_access_token_res = app_access_token_res.json()
  132. if app_access_token_res['code'] != 0:
  133. return redirect("/?error=%s" % app_access_token_res)
  134. res = requests.post(FEISHU_OAUTH.get("user_access_token_url"),
  135. data=json.dumps({
  136. "grant_type": FEISHU_OAUTH.get("grant_type"),
  137. "code": request.args.get('code')
  138. }),
  139. headers={
  140. "Content-Type": "application/json; charset=utf-8",
  141. 'Authorization': f"Bearer {app_access_token_res['app_access_token']}"
  142. })
  143. res = res.json()
  144. if res['code'] != 0:
  145. return redirect("/?error=%s" % res["message"])
  146. if "contact:user.email:readonly" not in res["data"]["scope"].split(" "):
  147. return redirect("/?error=contact:user.email:readonly not in scope")
  148. session["access_token"] = res["data"]["access_token"]
  149. session["access_token_from"] = "feishu"
  150. user_info = user_info_from_feishu(session["access_token"])
  151. email_address = user_info["email"]
  152. users = UserService.query(email=email_address)
  153. user_id = get_uuid()
  154. if not users:
  155. # User isn't try to register
  156. try:
  157. try:
  158. avatar = download_img(user_info["avatar_url"])
  159. except Exception as e:
  160. stat_logger.exception(e)
  161. avatar = ""
  162. users = user_register(user_id, {
  163. "access_token": session["access_token"],
  164. "email": email_address,
  165. "avatar": avatar,
  166. "nickname": user_info["en_name"],
  167. "login_channel": "feishu",
  168. "last_login_time": get_format_time(),
  169. "is_superuser": False,
  170. })
  171. if not users:
  172. raise Exception(f'Fail to register {email_address}.')
  173. if len(users) > 1:
  174. raise Exception(f'Same email: {email_address} exists!')
  175. # Try to log in
  176. user = users[0]
  177. login_user(user)
  178. return redirect("/?auth=%s" % user.get_id())
  179. except Exception as e:
  180. rollback_user_registration(user_id)
  181. stat_logger.exception(e)
  182. return redirect("/?error=%s" % str(e))
  183. # User has already registered, try to log in
  184. user = users[0]
  185. user.access_token = get_uuid()
  186. login_user(user)
  187. user.save()
  188. return redirect("/?auth=%s" % user.get_id())
  189. def user_info_from_feishu(access_token):
  190. import requests
  191. headers = {"Content-Type": "application/json; charset=utf-8",
  192. 'Authorization': f"Bearer {access_token}"}
  193. res = requests.get(
  194. f"https://open.feishu.cn/open-apis/authen/v1/user_info",
  195. headers=headers)
  196. user_info = res.json()["data"]
  197. user_info["email"] = None if user_info.get("email") == "" else user_info["email"]
  198. return user_info
  199. def user_info_from_github(access_token):
  200. import requests
  201. headers = {"Accept": "application/json",
  202. 'Authorization': f"token {access_token}"}
  203. res = requests.get(
  204. f"https://api.github.com/user?access_token={access_token}",
  205. headers=headers)
  206. user_info = res.json()
  207. email_info = requests.get(
  208. f"https://api.github.com/user/emails?access_token={access_token}",
  209. headers=headers).json()
  210. user_info["email"] = next(
  211. (email for email in email_info if email['primary'] == True),
  212. None)["email"]
  213. return user_info
  214. @manager.route("/logout", methods=['GET'])
  215. @login_required
  216. def log_out():
  217. current_user.access_token = ""
  218. current_user.save()
  219. logout_user()
  220. return get_json_result(data=True)
  221. @manager.route("/setting", methods=["POST"])
  222. @login_required
  223. def setting_user():
  224. update_dict = {}
  225. request_data = request.json
  226. if request_data.get("password"):
  227. new_password = request_data.get("new_password")
  228. if not check_password_hash(
  229. current_user.password, decrypt(request_data["password"])):
  230. return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg='Password error!')
  231. if new_password:
  232. update_dict["password"] = generate_password_hash(decrypt(new_password))
  233. for k in request_data.keys():
  234. if k in ["password", "new_password"]:
  235. continue
  236. update_dict[k] = request_data[k]
  237. try:
  238. UserService.update_by_id(current_user.id, update_dict)
  239. return get_json_result(data=True)
  240. except Exception as e:
  241. stat_logger.exception(e)
  242. return get_json_result(data=False, retmsg='Update failure!', retcode=RetCode.EXCEPTION_ERROR)
  243. @manager.route("/info", methods=["GET"])
  244. @login_required
  245. def user_profile():
  246. return get_json_result(data=current_user.to_dict())
  247. def rollback_user_registration(user_id):
  248. try:
  249. UserService.delete_by_id(user_id)
  250. except Exception as e:
  251. pass
  252. try:
  253. TenantService.delete_by_id(user_id)
  254. except Exception as e:
  255. pass
  256. try:
  257. u = UserTenantService.query(tenant_id=user_id)
  258. if u:
  259. UserTenantService.delete_by_id(u[0].id)
  260. except Exception as e:
  261. pass
  262. try:
  263. TenantLLM.delete().where(TenantLLM.tenant_id == user_id).execute()
  264. except Exception as e:
  265. pass
  266. def user_register(user_id, user):
  267. user["id"] = user_id
  268. tenant = {
  269. "id": user_id,
  270. "name": user["nickname"] + "‘s Kingdom",
  271. "llm_id": CHAT_MDL,
  272. "embd_id": EMBEDDING_MDL,
  273. "asr_id": ASR_MDL,
  274. "parser_ids": PARSERS,
  275. "img2txt_id": IMAGE2TEXT_MDL,
  276. "rerank_id": RERANK_MDL
  277. }
  278. usr_tenant = {
  279. "tenant_id": user_id,
  280. "user_id": user_id,
  281. "invited_by": user_id,
  282. "role": UserTenantRole.OWNER
  283. }
  284. file_id = get_uuid()
  285. file = {
  286. "id": file_id,
  287. "parent_id": file_id,
  288. "tenant_id": user_id,
  289. "created_by": user_id,
  290. "name": "/",
  291. "type": FileType.FOLDER.value,
  292. "size": 0,
  293. "location": "",
  294. }
  295. tenant_llm = []
  296. for llm in LLMService.query(fid=LLM_FACTORY):
  297. tenant_llm.append({"tenant_id": user_id,
  298. "llm_factory": LLM_FACTORY,
  299. "llm_name": llm.llm_name,
  300. "model_type": llm.model_type,
  301. "api_key": API_KEY,
  302. "api_base": LLM_BASE_URL
  303. })
  304. if not UserService.save(**user):
  305. return
  306. TenantService.insert(**tenant)
  307. UserTenantService.insert(**usr_tenant)
  308. TenantLLMService.insert_many(tenant_llm)
  309. FileService.insert(file)
  310. return UserService.query(email=user["email"])
  311. @manager.route("/register", methods=["POST"])
  312. @validate_request("nickname", "email", "password")
  313. def user_add():
  314. req = request.json
  315. email_address = req["email"]
  316. # Validate the email address
  317. if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", email_address):
  318. return get_json_result(data=False,
  319. retmsg=f'Invalid email address: {email_address}!',
  320. retcode=RetCode.OPERATING_ERROR)
  321. # Check if the email address is already used
  322. if UserService.query(email=email_address):
  323. return get_json_result(
  324. data=False,
  325. retmsg=f'Email: {email_address} has already registered!',
  326. retcode=RetCode.OPERATING_ERROR)
  327. # Construct user info data
  328. nickname = req["nickname"]
  329. user_dict = {
  330. "access_token": get_uuid(),
  331. "email": email_address,
  332. "nickname": nickname,
  333. "password": decrypt(req["password"]),
  334. "login_channel": "password",
  335. "last_login_time": get_format_time(),
  336. "is_superuser": False,
  337. }
  338. user_id = get_uuid()
  339. try:
  340. users = user_register(user_id, user_dict)
  341. if not users:
  342. raise Exception(f'Fail to register {email_address}.')
  343. if len(users) > 1:
  344. raise Exception(f'Same email: {email_address} exists!')
  345. user = users[0]
  346. login_user(user)
  347. return construct_response(data=user.to_json(),
  348. auth=user.get_id(),
  349. retmsg=f"{nickname}, welcome aboard!")
  350. except Exception as e:
  351. rollback_user_registration(user_id)
  352. stat_logger.exception(e)
  353. return get_json_result(data=False,
  354. retmsg=f'User registration failure, error: {str(e)}',
  355. retcode=RetCode.EXCEPTION_ERROR)
  356. @manager.route("/tenant_info", methods=["GET"])
  357. @login_required
  358. def tenant_info():
  359. try:
  360. tenants = TenantService.get_by_user_id(current_user.id)[0]
  361. return get_json_result(data=tenants)
  362. except Exception as e:
  363. return server_error_response(e)
  364. @manager.route("/set_tenant_info", methods=["POST"])
  365. @login_required
  366. @validate_request("tenant_id", "asr_id", "embd_id", "img2txt_id", "llm_id")
  367. def set_tenant_info():
  368. req = request.json
  369. try:
  370. tid = req["tenant_id"]
  371. del req["tenant_id"]
  372. TenantService.update_by_id(tid, req)
  373. return get_json_result(data=True)
  374. except Exception as e:
  375. return server_error_response(e)