Coverage for downtify/auth_routes.py: 84%

347 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""HTTP routes for signing in, pairing apps and the server's identity. 

2 

3The rules for who may call what live in :mod:`downtify.auth` 

4(:data:`downtify.auth.RULES`); these routes only do the work. Listed in 

5:mod:`downtify.api`'s module docstring with the rest of the API. 

6""" 

7 

8from __future__ import annotations 

9 

10import asyncio 

11from ipaddress import ip_address 

12from typing import Any, Optional 

13 

14from fastapi import APIRouter, HTTPException, Request, Response 

15from fastapi.responses import RedirectResponse 

16from loguru import logger 

17 

18from . import api 

19from .auth import ( 

20 SESSION_COOKIE, 

21 SESSION_TTL, 

22 AuthStore, 

23 Principal, 

24 clean_device_name, 

25 client_ip, 

26 identify_offloop, 

27 open_principal, 

28 session_cookie, 

29 trusted_proxies_from_env, 

30) 

31from .oidc import clean_oidc_username 

32from .server_identity import server_info 

33from .server_port import ( 

34 MAX_PORT, 

35 MIN_PORT, 

36 PortError, 

37 can_restart, 

38 clean_port, 

39 in_docker, 

40 locked_by, 

41 port_available, 

42 request_restart, 

43 resolve_port, 

44) 

45from .users import MIN_PASSWORD_LENGTH, ROLE_ADMIN 

46 

47router = APIRouter() 

48 

49_TRUSTED = trusted_proxies_from_env() 

50_OIDC_STATE_COOKIE = 'downtify_oidc_state' 

51_OIDC_TTL_SECONDS = 600 

52 

53 

54def _store() -> AuthStore: 

55 if api.state.auth is None: 

56 raise HTTPException(status_code=500, detail='Sign-in is not ready') 

57 return api.state.auth 

58 

59 

60def _ip(request: Request) -> str: 

61 return client_ip(request.scope, _TRUSTED) 

62 

63 

64def _principal(request: Request) -> Optional[Principal]: 

65 return (request.scope.get('state') or {}).get('principal') 

66 

67 

68def _me(request: Request) -> Principal: 

69 """The signed-in user making *request* (the middleware made sure 

70 there is one).""" 

71 

72 principal = _principal(request) 

73 if principal is None or not principal.user_id: 

74 raise HTTPException(status_code=401, detail='Sign in required') 

75 return principal 

76 

77 

78def _own_device(request: Request, device_id: str) -> dict[str, Any]: 

79 """*device_id*, when the user may manage it (theirs, or anyone's for 

80 an admin); else 404.""" 

81 

82 me = _me(request) 

83 device = _store().get_device(device_id) 

84 if ( 

85 device is None 

86 or device.get('revoked_at') 

87 or (not me.is_admin and int(device['user_id']) != me.user_id) 

88 ): 

89 raise HTTPException(status_code=404, detail='Device not found') 

90 return device 

91 

92 

93def _is_https(request: Request) -> bool: 

94 if request.url.scheme == 'https': 

95 return True 

96 peer = request.client.host if request.client else '' 

97 forwarded = request.headers.get('x-forwarded-proto', '') 

98 return bool( 

99 _TRUSTED 

100 and forwarded.lower() == 'https' 

101 and any(_in(peer, net) for net in _TRUSTED) 

102 ) 

103 

104 

105def _in(address: str, network: Any) -> bool: 

106 try: 

107 return ip_address(address) in network 

108 except ValueError: 

109 return False 

110 

111 

112def _set_session(response: Response, request: Request, token: str) -> None: 

113 response.set_cookie( 

114 SESSION_COOKIE, 

115 token, 

116 max_age=int(SESSION_TTL.total_seconds()), 

117 httponly=True, 

118 samesite='lax', 

119 secure=_is_https(request), 

120 path='/', 

121 ) 

122 

123 

124def _too_many(retry_after: int) -> HTTPException: 

125 return HTTPException( 

126 status_code=429, 

127 detail='Too many attempts. Try again later.', 

128 headers={'Retry-After': str(retry_after)}, 

129 ) 

130 

131 

132async def _json(request: Request) -> dict[str, Any]: 

133 try: 

134 payload = await request.json() 

135 except Exception: 

136 return {} 

137 return payload if isinstance(payload, dict) else {} 

138 

139 

140# ── Server identity ───────────────────────────────────────────────────── 

141 

142 

143@router.get('/api/server/info') 

144def get_server_info() -> dict[str, Any]: 

145 """Who this server is and what it can do - public, for an app to 

146 check an address before it has credentials.""" 

147 

148 identity = api.state.identity 

149 if identity is None: 

150 raise HTTPException(status_code=503, detail='Starting up') 

151 transcoder = getattr(api.state, 'transcoder', None) 

152 result = server_info( 

153 identity, 

154 version=api.state.version, 

155 require_sign_in=not (api.state.auth and api.state.auth.auth_disabled), 

156 password_sign_in=bool( 

157 api.state.auth 

158 and not api.state.auth.auth_disabled 

159 and getattr(api.state, 'local_login_enabled', True) 

160 ), 

161 transcoding=transcoder.capability() if transcoder else None, 

162 ) 

163 result['library_only'] = api.state.settings.get('library_only') is True 

164 result['capabilities']['playlist_editing'] = True 

165 return result 

166 

167 

168@router.patch('/api/server') 

169async def update_server(request: Request) -> dict[str, Any]: 

170 """Rename the server (``{name}``) - what apps and LAN discovery show.""" 

171 

172 identity = api.state.identity 

173 if identity is None: 

174 raise HTTPException(status_code=503, detail='Starting up') 

175 payload = await _json(request) 

176 try: 

177 await asyncio.to_thread(identity.set_name, payload.get('name')) 

178 except ValueError as exc: 

179 raise HTTPException(status_code=400, detail=str(exc)) from exc 

180 announcer = getattr(api.state, 'discovery', None) 

181 if announcer is not None: 

182 await announcer.update(identity.name) 

183 return get_server_info() 

184 

185 

186def _port_status() -> dict[str, Any]: 

187 identity = api.state.identity 

188 listen = api.state.listen or {} 

189 saved = identity.port if identity else None 

190 current = int(listen.get('port') or 0) 

191 source = str(listen.get('source') or 'default') 

192 # What the next start would use, with the environment as it is now. 

193 cli = current if source == '--port' else None 

194 next_port, next_source = resolve_port(cli, saved) 

195 return { 

196 'port': current, 

197 'saved': saved, 

198 'next': next_port, 

199 'locked_by': locked_by(next_source), 

200 'in_docker': in_docker(), 

201 'can_restart': can_restart(), 

202 'min': MIN_PORT, 

203 'max': MAX_PORT, 

204 } 

205 

206 

207@router.get('/api/server/port') 

208def get_server_port() -> dict[str, Any]: 

209 """The port the server listens on and the one it starts on next: 

210 ``{port, saved, next, locked_by, in_docker, can_restart, min, max}``. 

211 ``locked_by`` names what chose the port instead of Settings 

212 (``DOWNTIFY_PORT``, ``PORT`` or ``--port``), ``''`` when nothing.""" 

213 

214 if api.state.identity is None: 

215 raise HTTPException(status_code=503, detail='Starting up') 

216 return _port_status() 

217 

218 

219@router.put('/api/server/port') 

220async def set_server_port(request: Request) -> dict[str, Any]: 

221 """Choose the port: ``{port, restart}``. Saved for the next start; 

222 ``restart: true`` restarts the server on it right away (the response 

223 comes first). ``409`` when the environment or the command line sets 

224 the port, or the port is taken.""" 

225 

226 identity = api.state.identity 

227 if identity is None: 

228 raise HTTPException(status_code=503, detail='Starting up') 

229 status = _port_status() 

230 if status['locked_by']: 

231 raise HTTPException( 

232 status_code=409, 

233 detail=f'The port is set by {status["locked_by"]}', 

234 ) 

235 payload = await _json(request) 

236 try: 

237 port = clean_port(payload.get('port')) 

238 except PortError as exc: 

239 raise HTTPException(status_code=400, detail=str(exc)) from exc 

240 host = str((api.state.listen or {}).get('host') or '0.0.0.0') 

241 if port != status['port'] and not await asyncio.to_thread( 

242 port_available, host, port 

243 ): 

244 raise HTTPException( 

245 status_code=409, detail=f'Port {port} is already in use' 

246 ) 

247 await asyncio.to_thread(identity.set_port, port) 

248 await api.log_activity( 

249 request, 'settings_changed', 'port', {'keys': ['port']} 

250 ) 

251 restart = bool(payload.get('restart')) and port != status['port'] 

252 if restart and can_restart(): 

253 logger.warning('Port changed to {}: restarting', port) 

254 # After this response has gone out. 

255 asyncio.get_running_loop().call_later(0.5, request_restart) 

256 else: 

257 restart = False 

258 logger.info('Port {} saved for the next start', port) 

259 return {**_port_status(), 'restarting': restart} 

260 

261 

262# ── Status, sign in and out ───────────────────────────────────────────── 

263 

264 

265def _status_reads( 

266 store: AuthStore, principal: Optional[Principal], bad: bool 

267) -> tuple[ 

268 Optional[Principal], 

269 Optional[dict[str, Any]], 

270 Optional[dict[str, Any]], 

271 Any, 

272]: 

273 """The database reads ``GET /api/auth/status`` needs, run on a worker 

274 thread: who the request is when sign-in is off, the account, the 

275 paired device's name and the signed-out notice.""" 

276 

277 if principal is None and not bad: 

278 principal = open_principal(store) 

279 user = None 

280 device = None 

281 if principal is not None: 

282 user = store.users.get(principal.user_id) 

283 if principal.kind == 'device': 

284 found = store.get_device(principal.device_id) 

285 device = { 

286 'id': principal.device_id, 

287 'name': (found or {}).get('name'), 

288 } 

289 notice = None if principal or store.auth_disabled else store.users.notice() 

290 return principal, user, device, notice 

291 

292 

293@router.get('/api/auth/status') 

294async def auth_status(request: Request) -> dict[str, Any]: 

295 """Who this request is signed in as. 

296 

297 ``signed_in`` is what the web app checks before showing the sign-in 

298 page; ``via`` is ``session`` (a browser), ``device`` (a paired app) or 

299 ``null``; ``user`` is ``{id, username, role, default_password}``. 

300 ``notice`` (only while signed out) is the one-time "accounts are 

301 here" message for a server upgraded from a version without them: 

302 ``{username, password}`` - ``password`` is ``null`` when the old 

303 sign-in password was kept. 

304 """ 

305 

306 store = _store() 

307 principal, bad = await identify_offloop(request.scope, store, _ip(request)) 

308 principal, user, device, notice = await asyncio.to_thread( 

309 _status_reads, store, principal, bad 

310 ) 

311 return { 

312 'require_sign_in': not store.auth_disabled, 

313 'auth_disabled': store.auth_disabled, 

314 'local_login_enabled': bool( 

315 getattr(api.state, 'local_login_enabled', True) 

316 and not store.auth_disabled 

317 ), 

318 'oidc_enabled': bool( 

319 getattr(api.state, 'oidc', None) and not store.auth_disabled 

320 ), 

321 'min_password_length': MIN_PASSWORD_LENGTH, 

322 'signed_in': principal is not None, 

323 'via': principal.kind if principal else None, 

324 'user': user, 

325 'device': device, 

326 'notice': notice, 

327 } 

328 

329 

330def _oidc_callback_uri(request: Request) -> str: 

331 provider = getattr(api.state, 'oidc', None) 

332 if provider is None: 

333 raise HTTPException(status_code=404, detail='OIDC is not configured') 

334 return provider.config.redirect_uri or str( 

335 request.url_for('oidc_callback') 

336 ) 

337 

338 

339def _oidc_failure() -> RedirectResponse: 

340 return RedirectResponse('/?auth_error=oidc', status_code=303) 

341 

342 

343@router.get('/api/auth/oidc', name='oidc_login') 

344async def oidc_login(request: Request) -> Response: 

345 """Start the OIDC Authorization Code flow with PKCE.""" 

346 

347 store = _store() 

348 provider = getattr(api.state, 'oidc', None) 

349 if provider is None or store.auth_disabled: 

350 raise HTTPException(status_code=404, detail='OIDC is not enabled') 

351 try: 

352 authorization_url, state = await provider.begin( 

353 _oidc_callback_uri(request) 

354 ) 

355 except Exception as exc: 

356 logger.warning('OIDC authorization could not start: {}', exc) 

357 raise HTTPException( 

358 status_code=503, detail='Identity provider is unavailable' 

359 ) from exc 

360 response = RedirectResponse(authorization_url, status_code=303) 

361 response.set_cookie( 

362 _OIDC_STATE_COOKIE, 

363 state, 

364 max_age=_OIDC_TTL_SECONDS, 

365 httponly=True, 

366 samesite='lax', 

367 secure=_is_https(request), 

368 path='/api/auth/oidc', 

369 ) 

370 return response 

371 

372 

373@router.get('/api/auth/oidc/callback', name='oidc_callback') 

374async def oidc_callback(request: Request) -> Response: 

375 """Validate the provider response and create a local web session.""" 

376 

377 provider = getattr(api.state, 'oidc', None) 

378 store = _store() 

379 if provider is None or store.auth_disabled: 

380 raise HTTPException(status_code=404, detail='OIDC is not enabled') 

381 state = request.query_params.get('state', '') 

382 cookie_state = request.cookies.get(_OIDC_STATE_COOKIE, '') 

383 code = request.query_params.get('code', '') 

384 if request.query_params.get('error') or not code: 

385 response = _oidc_failure() 

386 response.delete_cookie(_OIDC_STATE_COOKIE, path='/api/auth/oidc') 

387 return response 

388 try: 

389 claims, asserted_username, role = await provider.authenticate( 

390 code=code, 

391 state=state, 

392 cookie_state=cookie_state, 

393 callback_uri=_oidc_callback_uri(request), 

394 ) 

395 username = clean_oidc_username( 

396 asserted_username, provider.config.issuer, claims['sub'] 

397 ) 

398 user = await asyncio.to_thread( 

399 store.users._get_or_create_oidc_user, 

400 provider.config.issuer, 

401 claims['sub'], 

402 username, 

403 role, 

404 ) 

405 except Exception as exc: 

406 logger.warning('OIDC sign-in rejected: {}', exc) 

407 response = _oidc_failure() 

408 response.delete_cookie(_OIDC_STATE_COOKIE, path='/api/auth/oidc') 

409 return response 

410 

411 ip = _ip(request) 

412 await asyncio.to_thread(store.users.record_login, user['id'], ip) 

413 if user['role'] == ROLE_ADMIN: 

414 await asyncio.to_thread(store.users.clear_notice) 

415 if api.state.activity is not None: 

416 await asyncio.to_thread( 

417 api.state.activity.record, 

418 'login', 

419 user_id=user['id'], 

420 username=user['username'], 

421 client=api.client_label(request, None), 

422 ip=ip, 

423 ) 

424 token = await asyncio.to_thread( 

425 store.create_session, 

426 user['id'], 

427 ip, 

428 request.headers.get('user-agent', ''), 

429 ) 

430 response = RedirectResponse('/', status_code=303) 

431 response.delete_cookie(_OIDC_STATE_COOKIE, path='/api/auth/oidc') 

432 _set_session(response, request, token) 

433 return response 

434 

435 

436@router.post('/api/auth/login') 

437async def login(request: Request, response: Response) -> dict[str, Any]: 

438 """Sign a browser in: ``{username, password}`` -> ``{signed_in, 

439 user}``. Rate-limited per address.""" 

440 

441 store = _store() 

442 if store.auth_disabled: 

443 raise HTTPException( 

444 status_code=409, 

445 detail='Sign-in is turned off (DOWNTIFY_DISABLE_AUTH)', 

446 ) 

447 if not getattr(api.state, 'local_login_enabled', True): 

448 raise HTTPException( 

449 status_code=409, 

450 detail='Password sign-in is turned off ' 

451 '(DOWNTIFY_DISABLE_LOCAL_LOGIN)', 

452 ) 

453 ip = _ip(request) 

454 wait = api.state.login_limiter.retry_after(ip) 

455 if wait: 

456 raise _too_many(wait) 

457 payload = await _json(request) 

458 username = str(payload.get('username') or '').strip()[:64] 

459 password = str(payload.get('password') or '') 

460 user = await asyncio.to_thread( 

461 store.users.authenticate, username, password 

462 ) 

463 log = api.state.activity 

464 if user is None: 

465 api.state.login_limiter.fail(ip) 

466 logger.warning('Sign-in: wrong username or password from {}', ip) 

467 if log is not None: 

468 await asyncio.to_thread( 

469 log.record, 

470 'login_failed', 

471 username=username, 

472 summary=username, 

473 client=api.client_label(request, None), 

474 ip=ip, 

475 ) 

476 raise HTTPException( 

477 status_code=401, detail='Wrong username or password' 

478 ) 

479 api.state.login_limiter.reset(ip) 

480 token = await asyncio.to_thread( 

481 store.create_session, 

482 user['id'], 

483 ip, 

484 request.headers.get('user-agent', ''), 

485 ) 

486 await asyncio.to_thread(store.users.record_login, user['id'], ip) 

487 if user['role'] == ROLE_ADMIN: 

488 # An admin has seen the server with accounts: the notice is done. 

489 await asyncio.to_thread(store.users.clear_notice) 

490 if log is not None: 

491 await asyncio.to_thread( 

492 log.record, 

493 'login', 

494 user_id=user['id'], 

495 username=user['username'], 

496 client=api.client_label(request, None), 

497 ip=ip, 

498 ) 

499 _set_session(response, request, token) 

500 return {'signed_in': True, 'user': user} 

501 

502 

503@router.post('/api/auth/logout') 

504async def logout(request: Request, response: Response) -> dict[str, Any]: 

505 """End this browser's session (a no-op for one that has none).""" 

506 

507 token = session_cookie(request.scope) 

508 store = api.state.auth 

509 if token and store is not None: 

510 user = await asyncio.to_thread(store.session_user, token) 

511 await asyncio.to_thread(store.end_session, token) 

512 log = api.state.activity 

513 if user is not None and log is not None: 

514 await asyncio.to_thread( 

515 log.record, 

516 'logout', 

517 user_id=user['id'], 

518 username=user['username'], 

519 client=api.client_label(request, None), 

520 ip=_ip(request), 

521 ) 

522 response.delete_cookie(SESSION_COOKIE, path='/') 

523 response.delete_cookie(_OIDC_STATE_COOKIE, path='/api/auth/oidc') 

524 return {'signed_in': False} 

525 

526 

527# ── Paired devices ────────────────────────────────────────────────────── 

528 

529 

530@router.get('/api/auth/devices') 

531def list_devices(request: Request) -> list[dict[str, Any]]: 

532 """The user's paired devices - everyone's for an admin (each with 

533 ``user_id`` and ``username``).""" 

534 

535 me = _me(request) 

536 return _store().list_devices(None if me.is_admin else me.user_id) 

537 

538 

539@router.patch('/api/auth/devices/{device_id}') 

540async def rename_device(device_id: str, request: Request) -> dict[str, Any]: 

541 store = _store() 

542 await asyncio.to_thread(_own_device, request, device_id) 

543 payload = await _json(request) 

544 if not await asyncio.to_thread( 

545 store.rename_device, device_id, str(payload.get('name') or '') 

546 ): 

547 raise HTTPException(status_code=404, detail='Device not found') 

548 found = await asyncio.to_thread(store.get_device, device_id) 

549 return found or {} 

550 

551 

552@router.delete('/api/auth/devices/{device_id}') 

553async def revoke_device(device_id: str, request: Request) -> dict[str, Any]: 

554 """Unpair a device: its token and signed URLs stop working and its 

555 WebSocket is closed.""" 

556 

557 store = _store() 

558 device = await asyncio.to_thread(_own_device, request, device_id) 

559 if not await asyncio.to_thread(store.revoke_device, device_id): 

560 raise HTTPException(status_code=404, detail='Device not found') 

561 await api.state.connections.close_device(device_id) 

562 await api.log_activity( 

563 request, 

564 'device_unpaired', 

565 str(device.get('name') or device_id), 

566 {'device_id': device_id, 'owner': device.get('username')}, 

567 ) 

568 logger.info('Unpaired device {}', device_id) 

569 return {'id': device_id, 'revoked': True} 

570 

571 

572@router.post('/api/auth/revoke-all') 

573async def revoke_all(response: Response) -> dict[str, Any]: 

574 """Sign out everything: every user's devices and browsers (this one 

575 too) and every signed URL. Admins only.""" 

576 

577 await asyncio.to_thread(_store().revoke_everything) 

578 await api.state.connections.close_device('') 

579 for user in await asyncio.to_thread(_store().users.list): 

580 await api.state.connections.close_user(user['id']) 

581 response.delete_cookie(SESSION_COOKIE, path='/') 

582 logger.warning('Signed out every device and browser') 

583 return {'revoked': True} 

584 

585 

586# ── Pairing ───────────────────────────────────────────────────────────── 

587 

588 

589def _own_pairing(request: Request, pairing_id: str) -> None: 

590 me = _me(request) 

591 owner = api.state.pairing.owner(pairing_id) 

592 if owner is not None and owner != me.user_id and not me.is_admin: 

593 raise HTTPException(status_code=404, detail='Pairing not found') 

594 

595 

596@router.post('/api/auth/pairing') 

597def start_pairing(request: Request) -> dict[str, Any]: 

598 """Start pairing an app to the signed-in user's account: 

599 ``{pairing_id, code, expires_in}``. The page shows the code (and a 

600 QR code carrying it) and follows the pairing with 

601 ``GET /api/auth/pairing/{pairing_id}`` or the ``device_paired`` 

602 WebSocket message.""" 

603 

604 _store() 

605 return api.state.pairing.create(_me(request).user_id) 

606 

607 

608@router.get('/api/auth/pairing/{pairing_id}') 

609def pairing_status(pairing_id: str, request: Request) -> dict[str, Any]: 

610 _own_pairing(request, pairing_id) 

611 return api.state.pairing.status(pairing_id) 

612 

613 

614@router.delete('/api/auth/pairing/{pairing_id}') 

615def cancel_pairing(pairing_id: str, request: Request) -> dict[str, Any]: 

616 _own_pairing(request, pairing_id) 

617 api.state.pairing.cancel(pairing_id) 

618 return {'cancelled': True} 

619 

620 

621@router.post('/api/auth/pair') 

622async def pair(request: Request) -> dict[str, Any]: 

623 """An app trades a pairing code for its device token: 

624 ``{code, device_name, platform}`` -> ``{token, device, server, 

625 user}``. The device belongs to the user who showed the code. 

626 

627 Public and rate-limited per address; a code works once and for five 

628 minutes. The token is shown here once and never stored. 

629 """ 

630 

631 store = _store() 

632 ip = _ip(request) 

633 wait = api.state.pair_limiter.retry_after(ip) 

634 if wait: 

635 raise _too_many(wait) 

636 payload = await _json(request) 

637 pairing_id = api.state.pairing.claim(payload.get('code')) 

638 owner = ( 

639 api.state.pairing.owner(pairing_id) if pairing_id is not None else None 

640 ) 

641 user = None 

642 if owner: 

643 user = await asyncio.to_thread(store.users.get, owner) 

644 if pairing_id is None or user is None: 

645 api.state.pair_limiter.fail(ip) 

646 logger.warning('Pairing: wrong or expired code from {}', ip) 

647 raise HTTPException( 

648 status_code=401, detail='Wrong or expired pairing code' 

649 ) 

650 return await _new_device(payload, user, ip, pairing_id) 

651 

652 

653@router.post('/api/auth/token') 

654async def sign_in_device(request: Request) -> dict[str, Any]: 

655 """An app signs in with a username and password and gets its device 

656 token: ``{username, password, device_name, platform}`` -> ``{token, 

657 device, server, user}``, the same answer as ``POST /api/auth/pair``. 

658 The device belongs to that user. 

659 

660 Public and rate-limited per address together with ``POST 

661 /api/auth/login``, so switching between the two doesn't buy more 

662 tries. ``409`` while sign-in is turned off: pair with a code then. 

663 """ 

664 

665 store = _store() 

666 if store.auth_disabled: 

667 raise HTTPException( 

668 status_code=409, 

669 detail='Sign-in is turned off (DOWNTIFY_DISABLE_AUTH)', 

670 ) 

671 if not getattr(api.state, 'local_login_enabled', True): 

672 raise HTTPException( 

673 status_code=409, 

674 detail='Password sign-in is turned off ' 

675 '(DOWNTIFY_DISABLE_LOCAL_LOGIN)', 

676 ) 

677 ip = _ip(request) 

678 wait = api.state.login_limiter.retry_after(ip) 

679 if wait: 

680 raise _too_many(wait) 

681 payload = await _json(request) 

682 username = str(payload.get('username') or '').strip()[:64] 

683 password = str(payload.get('password') or '') 

684 user = await asyncio.to_thread( 

685 store.users.authenticate, username, password 

686 ) 

687 log = api.state.activity 

688 client = clean_device_name(payload.get('device_name')) 

689 if user is None: 

690 api.state.login_limiter.fail(ip) 

691 logger.warning('App sign-in: wrong username or password from {}', ip) 

692 if log is not None: 

693 await asyncio.to_thread( 

694 log.record, 

695 'login_failed', 

696 username=username, 

697 summary=username, 

698 client=client, 

699 ip=ip, 

700 ) 

701 raise HTTPException( 

702 status_code=401, detail='Wrong username or password' 

703 ) 

704 api.state.login_limiter.reset(ip) 

705 await asyncio.to_thread(store.users.record_login, user['id'], ip) 

706 if log is not None: 

707 await asyncio.to_thread( 

708 log.record, 

709 'login', 

710 user_id=user['id'], 

711 username=user['username'], 

712 client=client, 

713 ip=ip, 

714 ) 

715 return await _new_device(payload, user, ip, None) 

716 

717 

718async def _new_device( 

719 payload: dict[str, Any], 

720 user: dict[str, Any], 

721 ip: str, 

722 pairing_id: Optional[str], 

723) -> dict[str, Any]: 

724 """Make the device an app asked for (``device_name``, ``platform`` in 

725 *payload*) for *user*, tell their pages and the activity log, and 

726 answer with its token - shown here once and never stored. 

727 *pairing_id* is the pairing it completes, ``None`` for a sign-in.""" 

728 

729 store = _store() 

730 device, token = await asyncio.to_thread( 

731 store.create_device, 

732 str(payload.get('device_name') or ''), 

733 str(payload.get('platform') or ''), 

734 ip, 

735 user['id'], 

736 ) 

737 if pairing_id is not None: 

738 api.state.pairing.complete(pairing_id, device) 

739 await api.state.connections.send_user( 

740 user['id'], 

741 {'type': 'device_paired', 'pairing_id': pairing_id, 'device': device}, 

742 ) 

743 log = api.state.activity 

744 if log is not None: 

745 await asyncio.to_thread( 

746 log.record, 

747 'device_paired', 

748 user_id=user['id'], 

749 username=user['username'], 

750 summary=str(device.get('name') or ''), 

751 detail={'device_id': device.get('id')}, 

752 client=str(device.get('name') or ''), 

753 ip=ip, 

754 ) 

755 logger.info('Paired device {} ({})', device.get('name'), device.get('id')) 

756 identity = api.state.identity 

757 return { 

758 'token': token, 

759 'device': {'id': device.get('id'), 'name': device.get('name')}, 

760 'server': { 

761 'server_id': identity.server_id if identity else '', 

762 'name': identity.name if identity else '', 

763 }, 

764 'user': {'username': user['username'], 'role': user['role']}, 

765 } 

766 

767 

768@router.post('/api/auth/ws-ticket') 

769def ws_ticket(request: Request) -> dict[str, Any]: 

770 """A single-use ticket (60 s) for opening the WebSocket as 

771 ``/api/ws?client_id=…&ticket=…``, for a client that can't send an 

772 ``Authorization`` header with the handshake.""" 

773 

774 return {'ticket': api.state.ws_tickets.create(_me(request))}