auths.py 13 KB

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