auths.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. if Users.get_num_users() == 0:
  223. # Disable signup after the first user is created
  224. request.app.state.config.ENABLE_SIGNUP = False
  225. hashed = get_password_hash(form_data.password)
  226. user = Auths.insert_new_auth(
  227. form_data.email.lower(),
  228. hashed,
  229. form_data.name,
  230. form_data.profile_image_url,
  231. role,
  232. )
  233. if user:
  234. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  235. expires_at = None
  236. if expires_delta:
  237. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  238. token = create_token(
  239. data={"id": user.id},
  240. expires_delta=expires_delta,
  241. )
  242. datetime_expires_at = (
  243. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  244. if expires_at
  245. else None
  246. )
  247. # Set the cookie token
  248. response.set_cookie(
  249. key="token",
  250. value=token,
  251. expires=datetime_expires_at,
  252. httponly=True, # Ensures the cookie is not accessible via JavaScript
  253. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  254. secure=WEBUI_SESSION_COOKIE_SECURE,
  255. )
  256. if request.app.state.config.WEBHOOK_URL:
  257. post_webhook(
  258. request.app.state.config.WEBHOOK_URL,
  259. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  260. {
  261. "action": "signup",
  262. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  263. "user": user.model_dump_json(exclude_none=True),
  264. },
  265. )
  266. return {
  267. "token": token,
  268. "token_type": "Bearer",
  269. "expires_at": expires_at,
  270. "id": user.id,
  271. "email": user.email,
  272. "name": user.name,
  273. "role": user.role,
  274. "profile_image_url": user.profile_image_url,
  275. }
  276. else:
  277. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  278. except Exception as err:
  279. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  280. @router.get("/signout")
  281. async def signout(response: Response):
  282. response.delete_cookie("token")
  283. return {"status": True}
  284. ############################
  285. # AddUser
  286. ############################
  287. @router.post("/add", response_model=SigninResponse)
  288. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  289. if not validate_email_format(form_data.email.lower()):
  290. raise HTTPException(
  291. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  292. )
  293. if Users.get_user_by_email(form_data.email.lower()):
  294. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  295. try:
  296. print(form_data)
  297. hashed = get_password_hash(form_data.password)
  298. user = Auths.insert_new_auth(
  299. form_data.email.lower(),
  300. hashed,
  301. form_data.name,
  302. form_data.profile_image_url,
  303. form_data.role,
  304. )
  305. if user:
  306. token = create_token(data={"id": user.id})
  307. return {
  308. "token": token,
  309. "token_type": "Bearer",
  310. "id": user.id,
  311. "email": user.email,
  312. "name": user.name,
  313. "role": user.role,
  314. "profile_image_url": user.profile_image_url,
  315. }
  316. else:
  317. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  318. except Exception as err:
  319. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  320. ############################
  321. # GetAdminDetails
  322. ############################
  323. @router.get("/admin/details")
  324. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  325. if request.app.state.config.SHOW_ADMIN_DETAILS:
  326. admin_email = request.app.state.config.ADMIN_EMAIL
  327. admin_name = None
  328. print(admin_email, admin_name)
  329. if admin_email:
  330. admin = Users.get_user_by_email(admin_email)
  331. if admin:
  332. admin_name = admin.name
  333. else:
  334. admin = Users.get_first_user()
  335. if admin:
  336. admin_email = admin.email
  337. admin_name = admin.name
  338. return {
  339. "name": admin_name,
  340. "email": admin_email,
  341. }
  342. else:
  343. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  344. ############################
  345. # ToggleSignUp
  346. ############################
  347. @router.get("/admin/config")
  348. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  349. return {
  350. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  351. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  352. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  353. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  354. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  355. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  356. }
  357. class AdminConfig(BaseModel):
  358. SHOW_ADMIN_DETAILS: bool
  359. ENABLE_SIGNUP: bool
  360. DEFAULT_USER_ROLE: str
  361. JWT_EXPIRES_IN: str
  362. ENABLE_COMMUNITY_SHARING: bool
  363. ENABLE_MESSAGE_RATING: bool
  364. @router.post("/admin/config")
  365. async def update_admin_config(
  366. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  367. ):
  368. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  369. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  370. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  371. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  372. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  373. # Check if the input string matches the pattern
  374. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  375. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  376. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  377. form_data.ENABLE_COMMUNITY_SHARING
  378. )
  379. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  380. return {
  381. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  382. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  383. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  384. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  385. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  386. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  387. }
  388. ############################
  389. # API Key
  390. ############################
  391. # create api key
  392. @router.post("/api_key", response_model=ApiKey)
  393. async def create_api_key_(user=Depends(get_current_user)):
  394. api_key = create_api_key()
  395. success = Users.update_user_api_key_by_id(user.id, api_key)
  396. if success:
  397. return {
  398. "api_key": api_key,
  399. }
  400. else:
  401. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  402. # delete api key
  403. @router.delete("/api_key", response_model=bool)
  404. async def delete_api_key(user=Depends(get_current_user)):
  405. success = Users.update_user_api_key_by_id(user.id, None)
  406. return success
  407. # get api key
  408. @router.get("/api_key", response_model=ApiKey)
  409. async def get_api_key(user=Depends(get_current_user)):
  410. api_key = Users.get_user_api_key_by_id(user.id)
  411. if api_key:
  412. return {
  413. "api_key": api_key,
  414. }
  415. else:
  416. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)