auths.py 15 KB

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