auths.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import re
  2. import uuid
  3. from apps.webui.models.auths import (
  4. AddUserForm,
  5. ApiKey,
  6. Auths,
  7. SigninForm,
  8. SigninResponse,
  9. SignupForm,
  10. UpdatePasswordForm,
  11. UpdateProfileForm,
  12. UserResponse,
  13. )
  14. from apps.webui.models.users import Users
  15. from config import WEBUI_AUTH
  16. from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  17. from env import WEBUI_AUTH_TRUSTED_EMAIL_HEADER, WEBUI_AUTH_TRUSTED_NAME_HEADER
  18. from fastapi import APIRouter, Depends, HTTPException, Request, status
  19. from fastapi.responses import Response
  20. from pydantic import BaseModel
  21. from utils.misc import parse_duration, validate_email_format
  22. from utils.utils import (
  23. create_api_key,
  24. create_token,
  25. get_admin_user,
  26. get_current_user,
  27. get_password_hash,
  28. )
  29. from utils.webhook import post_webhook
  30. router = APIRouter()
  31. ############################
  32. # GetSessionUser
  33. ############################
  34. @router.get("/", response_model=UserResponse)
  35. async def get_session_user(
  36. request: Request, response: Response, user=Depends(get_current_user)
  37. ):
  38. token = create_token(
  39. data={"id": user.id},
  40. expires_delta=parse_duration(request.app.state.config.JWT_EXPIRES_IN),
  41. )
  42. # Set the cookie token
  43. response.set_cookie(
  44. key="token",
  45. value=token,
  46. httponly=True, # Ensures the cookie is not accessible via JavaScript
  47. )
  48. return {
  49. "id": user.id,
  50. "email": user.email,
  51. "name": user.name,
  52. "role": user.role,
  53. "profile_image_url": user.profile_image_url,
  54. }
  55. ############################
  56. # Update Profile
  57. ############################
  58. @router.post("/update/profile", response_model=UserResponse)
  59. async def update_profile(
  60. form_data: UpdateProfileForm, session_user=Depends(get_current_user)
  61. ):
  62. if session_user:
  63. user = Users.update_user_by_id(
  64. session_user.id,
  65. {"profile_image_url": form_data.profile_image_url, "name": form_data.name},
  66. )
  67. if user:
  68. return user
  69. else:
  70. raise HTTPException(400, detail=ERROR_MESSAGES.DEFAULT())
  71. else:
  72. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  73. ############################
  74. # Update Password
  75. ############################
  76. @router.post("/update/password", response_model=bool)
  77. async def update_password(
  78. form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
  79. ):
  80. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  81. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  82. if session_user:
  83. user = Auths.authenticate_user(session_user.email, form_data.password)
  84. if user:
  85. hashed = get_password_hash(form_data.new_password)
  86. return Auths.update_user_password_by_id(user.id, hashed)
  87. else:
  88. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
  89. else:
  90. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  91. ############################
  92. # SignIn
  93. ############################
  94. @router.post("/signin", response_model=SigninResponse)
  95. async def signin(request: Request, response: Response, form_data: SigninForm):
  96. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  97. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  98. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  99. trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  100. trusted_name = trusted_email
  101. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  102. trusted_name = request.headers.get(
  103. WEBUI_AUTH_TRUSTED_NAME_HEADER, trusted_email
  104. )
  105. if not Users.get_user_by_email(trusted_email.lower()):
  106. await signup(
  107. request,
  108. response,
  109. SignupForm(
  110. email=trusted_email, password=str(uuid.uuid4()), name=trusted_name
  111. ),
  112. )
  113. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  114. elif WEBUI_AUTH == False:
  115. admin_email = "admin@localhost"
  116. admin_password = "admin"
  117. if Users.get_user_by_email(admin_email.lower()):
  118. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  119. else:
  120. if Users.get_num_users() != 0:
  121. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  122. await signup(
  123. request,
  124. response,
  125. SignupForm(email=admin_email, password=admin_password, name="User"),
  126. )
  127. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  128. else:
  129. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  130. if user:
  131. token = create_token(
  132. data={"id": user.id},
  133. expires_delta=parse_duration(request.app.state.config.JWT_EXPIRES_IN),
  134. )
  135. # Set the cookie token
  136. response.set_cookie(
  137. key="token",
  138. value=token,
  139. httponly=True, # Ensures the cookie is not accessible via JavaScript
  140. )
  141. return {
  142. "token": token,
  143. "token_type": "Bearer",
  144. "id": user.id,
  145. "email": user.email,
  146. "name": user.name,
  147. "role": user.role,
  148. "profile_image_url": user.profile_image_url,
  149. }
  150. else:
  151. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  152. ############################
  153. # SignUp
  154. ############################
  155. @router.post("/signup", response_model=SigninResponse)
  156. async def signup(request: Request, response: Response, form_data: SignupForm):
  157. if (
  158. not request.app.state.config.ENABLE_SIGNUP
  159. and request.app.state.config.ENABLE_LOGIN_FORM
  160. and WEBUI_AUTH
  161. ):
  162. raise HTTPException(
  163. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  164. )
  165. if not validate_email_format(form_data.email.lower()):
  166. raise HTTPException(
  167. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  168. )
  169. if Users.get_user_by_email(form_data.email.lower()):
  170. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  171. try:
  172. role = (
  173. "admin"
  174. if Users.get_num_users() == 0
  175. else request.app.state.config.DEFAULT_USER_ROLE
  176. )
  177. hashed = get_password_hash(form_data.password)
  178. user = Auths.insert_new_auth(
  179. form_data.email.lower(),
  180. hashed,
  181. form_data.name,
  182. form_data.profile_image_url,
  183. role,
  184. )
  185. if user:
  186. token = create_token(
  187. data={"id": user.id},
  188. expires_delta=parse_duration(request.app.state.config.JWT_EXPIRES_IN),
  189. )
  190. # Set the cookie token
  191. response.set_cookie(
  192. key="token",
  193. value=token,
  194. httponly=True, # Ensures the cookie is not accessible via JavaScript
  195. )
  196. if request.app.state.config.WEBHOOK_URL:
  197. post_webhook(
  198. request.app.state.config.WEBHOOK_URL,
  199. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  200. {
  201. "action": "signup",
  202. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  203. "user": user.model_dump_json(exclude_none=True),
  204. },
  205. )
  206. return {
  207. "token": token,
  208. "token_type": "Bearer",
  209. "id": user.id,
  210. "email": user.email,
  211. "name": user.name,
  212. "role": user.role,
  213. "profile_image_url": user.profile_image_url,
  214. }
  215. else:
  216. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  217. except Exception as err:
  218. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  219. ############################
  220. # AddUser
  221. ############################
  222. @router.post("/add", response_model=SigninResponse)
  223. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  224. if not validate_email_format(form_data.email.lower()):
  225. raise HTTPException(
  226. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  227. )
  228. if Users.get_user_by_email(form_data.email.lower()):
  229. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  230. try:
  231. print(form_data)
  232. hashed = get_password_hash(form_data.password)
  233. user = Auths.insert_new_auth(
  234. form_data.email.lower(),
  235. hashed,
  236. form_data.name,
  237. form_data.profile_image_url,
  238. form_data.role,
  239. )
  240. if user:
  241. token = create_token(data={"id": user.id})
  242. return {
  243. "token": token,
  244. "token_type": "Bearer",
  245. "id": user.id,
  246. "email": user.email,
  247. "name": user.name,
  248. "role": user.role,
  249. "profile_image_url": user.profile_image_url,
  250. }
  251. else:
  252. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  253. except Exception as err:
  254. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  255. ############################
  256. # GetAdminDetails
  257. ############################
  258. @router.get("/admin/details")
  259. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  260. if request.app.state.config.SHOW_ADMIN_DETAILS:
  261. admin_email = request.app.state.config.ADMIN_EMAIL
  262. admin_name = None
  263. print(admin_email, admin_name)
  264. if admin_email:
  265. admin = Users.get_user_by_email(admin_email)
  266. if admin:
  267. admin_name = admin.name
  268. else:
  269. admin = Users.get_first_user()
  270. if admin:
  271. admin_email = admin.email
  272. admin_name = admin.name
  273. return {
  274. "name": admin_name,
  275. "email": admin_email,
  276. }
  277. else:
  278. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  279. ############################
  280. # ToggleSignUp
  281. ############################
  282. @router.get("/admin/config")
  283. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  284. return {
  285. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  286. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  287. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  288. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  289. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  290. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  291. }
  292. class AdminConfig(BaseModel):
  293. SHOW_ADMIN_DETAILS: bool
  294. ENABLE_SIGNUP: bool
  295. DEFAULT_USER_ROLE: str
  296. JWT_EXPIRES_IN: str
  297. ENABLE_COMMUNITY_SHARING: bool
  298. ENABLE_MESSAGE_RATING: bool
  299. @router.post("/admin/config")
  300. async def update_admin_config(
  301. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  302. ):
  303. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  304. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  305. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  306. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  307. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  308. # Check if the input string matches the pattern
  309. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  310. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  311. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  312. form_data.ENABLE_COMMUNITY_SHARING
  313. )
  314. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  315. return {
  316. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  317. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  318. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  319. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  320. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  321. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  322. }
  323. ############################
  324. # API Key
  325. ############################
  326. # create api key
  327. @router.post("/api_key", response_model=ApiKey)
  328. async def create_api_key_(user=Depends(get_current_user)):
  329. api_key = create_api_key()
  330. success = Users.update_user_api_key_by_id(user.id, api_key)
  331. if success:
  332. return {
  333. "api_key": api_key,
  334. }
  335. else:
  336. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  337. # delete api key
  338. @router.delete("/api_key", response_model=bool)
  339. async def delete_api_key(user=Depends(get_current_user)):
  340. success = Users.update_user_api_key_by_id(user.id, None)
  341. return success
  342. # get api key
  343. @router.get("/api_key", response_model=ApiKey)
  344. async def get_api_key(user=Depends(get_current_user)):
  345. api_key = Users.get_user_api_key_by_id(user.id)
  346. if api_key:
  347. return {
  348. "api_key": api_key,
  349. }
  350. else:
  351. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)