Просмотр исходного кода

caldav: log clean auth error with url/username, suppress stacktrace

ZiB 4 месяцев назад
Родитель
Сommit
5ac97137fb
2 измененных файлов с 19 добавлено и 1 удалено
  1. 11 0
      room_cal/api/__init__.py
  2. 8 1
      room_cal/store/_caldav.py

+ 11 - 0
room_cal/api/__init__.py

@@ -48,8 +48,19 @@ async def _lifespan(app: FastAPI):
     await task
     await task
 
 
 
 
+_log = __import__('logging').getLogger(__name__)
+
+
 def create_app() -> FastAPI:
 def create_app() -> FastAPI:
+  from caldav.lib.error import AuthorizationError
+
   app = FastAPI(title='room_cal', lifespan=_lifespan)
   app = FastAPI(title='room_cal', lifespan=_lifespan)
+
+  @app.exception_handler(AuthorizationError)
+  async def _caldav_auth_error(request: Request, exc: AuthorizationError):
+    _log.error('caldav: %s', exc)
+    return JSONResponse({'detail': str(exc)}, status_code=500)
+
   app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])
   app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])
   app.add_middleware(_AuthMiddleware)
   app.add_middleware(_AuthMiddleware)
   app.include_router(auth_router)
   app.include_router(auth_router)

+ 8 - 1
room_cal/store/_caldav.py

@@ -96,7 +96,14 @@ class Calendar:
   async def _get_calendar(self, client):
   async def _get_calendar(self, client):
     if self._cached_url is not None:
     if self._cached_url is not None:
       return client.calendar(url=self._cached_url)
       return client.calendar(url=self._cached_url)
-    principal = await client.principal()
+    from caldav.lib.error import AuthorizationError
+    try:
+      principal = await client.principal()
+    except AuthorizationError:
+      conn = self._resolved_connection()
+      raise AuthorizationError(
+        f"CalDAV auth failed for {conn['url']} (username={conn.get('username', '(none)')})"
+      ) from None
     calendars = await principal.get_calendars()
     calendars = await principal.get_calendars()
     for cal in calendars:
     for cal in calendars:
       if await cal.get_display_name() == self._calendar_name:
       if await cal.get_display_name() == self._calendar_name: