UserController.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Constants;
  7. using Jellyfin.Api.Extensions;
  8. using Jellyfin.Api.Helpers;
  9. using Jellyfin.Api.Models.UserDtos;
  10. using Jellyfin.Data.Enums;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller.Authentication;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Devices;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.Net;
  18. using MediaBrowser.Controller.QuickConnect;
  19. using MediaBrowser.Controller.Session;
  20. using MediaBrowser.Model.Configuration;
  21. using MediaBrowser.Model.Dto;
  22. using MediaBrowser.Model.Users;
  23. using Microsoft.AspNetCore.Authorization;
  24. using Microsoft.AspNetCore.Http;
  25. using Microsoft.AspNetCore.Mvc;
  26. using Microsoft.Extensions.Logging;
  27. namespace Jellyfin.Api.Controllers
  28. {
  29. /// <summary>
  30. /// User controller.
  31. /// </summary>
  32. [Route("Users")]
  33. public class UserController : BaseJellyfinApiController
  34. {
  35. private readonly IUserManager _userManager;
  36. private readonly ISessionManager _sessionManager;
  37. private readonly INetworkManager _networkManager;
  38. private readonly IDeviceManager _deviceManager;
  39. private readonly IAuthorizationContext _authContext;
  40. private readonly IServerConfigurationManager _config;
  41. private readonly ILogger _logger;
  42. private readonly IQuickConnect _quickConnectManager;
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="UserController"/> class.
  45. /// </summary>
  46. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  47. /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
  48. /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
  49. /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
  50. /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
  51. /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  52. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  53. /// <param name="quickConnectManager">Instance of the <see cref="IQuickConnect"/> interface.</param>
  54. public UserController(
  55. IUserManager userManager,
  56. ISessionManager sessionManager,
  57. INetworkManager networkManager,
  58. IDeviceManager deviceManager,
  59. IAuthorizationContext authContext,
  60. IServerConfigurationManager config,
  61. ILogger<UserController> logger,
  62. IQuickConnect quickConnectManager)
  63. {
  64. _userManager = userManager;
  65. _sessionManager = sessionManager;
  66. _networkManager = networkManager;
  67. _deviceManager = deviceManager;
  68. _authContext = authContext;
  69. _config = config;
  70. _logger = logger;
  71. _quickConnectManager = quickConnectManager;
  72. }
  73. /// <summary>
  74. /// Gets a list of users.
  75. /// </summary>
  76. /// <param name="isHidden">Optional filter by IsHidden=true or false.</param>
  77. /// <param name="isDisabled">Optional filter by IsDisabled=true or false.</param>
  78. /// <response code="200">Users returned.</response>
  79. /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the users.</returns>
  80. [HttpGet]
  81. [Authorize(Policy = Policies.DefaultAuthorization)]
  82. [ProducesResponseType(StatusCodes.Status200OK)]
  83. public ActionResult<IEnumerable<UserDto>> GetUsers(
  84. [FromQuery] bool? isHidden,
  85. [FromQuery] bool? isDisabled)
  86. {
  87. var users = Get(isHidden, isDisabled, false, false);
  88. return Ok(users);
  89. }
  90. /// <summary>
  91. /// Gets a list of publicly visible users for display on a login screen.
  92. /// </summary>
  93. /// <response code="200">Public users returned.</response>
  94. /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the public users.</returns>
  95. [HttpGet("Public")]
  96. [ProducesResponseType(StatusCodes.Status200OK)]
  97. public ActionResult<IEnumerable<UserDto>> GetPublicUsers()
  98. {
  99. // If the startup wizard hasn't been completed then just return all users
  100. if (!_config.Configuration.IsStartupWizardCompleted)
  101. {
  102. return Ok(Get(false, false, false, false));
  103. }
  104. return Ok(Get(false, false, true, true));
  105. }
  106. /// <summary>
  107. /// Gets a user by Id.
  108. /// </summary>
  109. /// <param name="userId">The user id.</param>
  110. /// <response code="200">User returned.</response>
  111. /// <response code="404">User not found.</response>
  112. /// <returns>An <see cref="UserDto"/> with information about the user or a <see cref="NotFoundResult"/> if the user was not found.</returns>
  113. [HttpGet("{userId}")]
  114. [Authorize(Policy = Policies.IgnoreParentalControl)]
  115. [ProducesResponseType(StatusCodes.Status200OK)]
  116. [ProducesResponseType(StatusCodes.Status404NotFound)]
  117. public ActionResult<UserDto> GetUserById([FromRoute, Required] Guid userId)
  118. {
  119. var user = _userManager.GetUserById(userId);
  120. if (user is null)
  121. {
  122. return NotFound("User not found");
  123. }
  124. var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString());
  125. return result;
  126. }
  127. /// <summary>
  128. /// Deletes a user.
  129. /// </summary>
  130. /// <param name="userId">The user id.</param>
  131. /// <response code="204">User deleted.</response>
  132. /// <response code="404">User not found.</response>
  133. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="NotFoundResult"/> if the user was not found.</returns>
  134. [HttpDelete("{userId}")]
  135. [Authorize(Policy = Policies.RequiresElevation)]
  136. [ProducesResponseType(StatusCodes.Status204NoContent)]
  137. [ProducesResponseType(StatusCodes.Status404NotFound)]
  138. public async Task<ActionResult> DeleteUser([FromRoute, Required] Guid userId)
  139. {
  140. var user = _userManager.GetUserById(userId);
  141. await _sessionManager.RevokeUserTokens(user.Id, null).ConfigureAwait(false);
  142. await _userManager.DeleteUserAsync(userId).ConfigureAwait(false);
  143. return NoContent();
  144. }
  145. /// <summary>
  146. /// Authenticates a user.
  147. /// </summary>
  148. /// <param name="userId">The user id.</param>
  149. /// <param name="pw">The password as plain text.</param>
  150. /// <param name="password">The password sha1-hash.</param>
  151. /// <response code="200">User authenticated.</response>
  152. /// <response code="403">Sha1-hashed password only is not allowed.</response>
  153. /// <response code="404">User not found.</response>
  154. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationResult"/>.</returns>
  155. [HttpPost("{userId}/Authenticate")]
  156. [ProducesResponseType(StatusCodes.Status200OK)]
  157. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  158. [ProducesResponseType(StatusCodes.Status404NotFound)]
  159. public async Task<ActionResult<AuthenticationResult>> AuthenticateUser(
  160. [FromRoute, Required] Guid userId,
  161. [FromQuery, Required] string pw,
  162. [FromQuery] string? password)
  163. {
  164. var user = _userManager.GetUserById(userId);
  165. if (user is null)
  166. {
  167. return NotFound("User not found");
  168. }
  169. if (!string.IsNullOrEmpty(password) && string.IsNullOrEmpty(pw))
  170. {
  171. return StatusCode(StatusCodes.Status403Forbidden, "Only sha1 password is not allowed.");
  172. }
  173. AuthenticateUserByName request = new AuthenticateUserByName
  174. {
  175. Username = user.Username,
  176. Pw = pw
  177. };
  178. return await AuthenticateUserByName(request).ConfigureAwait(false);
  179. }
  180. /// <summary>
  181. /// Authenticates a user by name.
  182. /// </summary>
  183. /// <param name="request">The <see cref="AuthenticateUserByName"/> request.</param>
  184. /// <response code="200">User authenticated.</response>
  185. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
  186. [HttpPost("AuthenticateByName")]
  187. [ProducesResponseType(StatusCodes.Status200OK)]
  188. public async Task<ActionResult<AuthenticationResult>> AuthenticateUserByName([FromBody, Required] AuthenticateUserByName request)
  189. {
  190. var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
  191. try
  192. {
  193. var result = await _sessionManager.AuthenticateNewSession(new AuthenticationRequest
  194. {
  195. App = auth.Client,
  196. AppVersion = auth.Version,
  197. DeviceId = auth.DeviceId,
  198. DeviceName = auth.Device,
  199. Password = request.Pw,
  200. RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(),
  201. Username = request.Username
  202. }).ConfigureAwait(false);
  203. return result;
  204. }
  205. catch (SecurityException e)
  206. {
  207. // rethrow adding IP address to message
  208. throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
  209. }
  210. }
  211. /// <summary>
  212. /// Authenticates a user with quick connect.
  213. /// </summary>
  214. /// <param name="request">The <see cref="QuickConnectDto"/> request.</param>
  215. /// <response code="200">User authenticated.</response>
  216. /// <response code="400">Missing token.</response>
  217. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
  218. [HttpPost("AuthenticateWithQuickConnect")]
  219. [ProducesResponseType(StatusCodes.Status200OK)]
  220. public ActionResult<AuthenticationResult> AuthenticateWithQuickConnect([FromBody, Required] QuickConnectDto request)
  221. {
  222. try
  223. {
  224. return _quickConnectManager.GetAuthorizedRequest(request.Secret);
  225. }
  226. catch (SecurityException e)
  227. {
  228. // rethrow adding IP address to message
  229. throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
  230. }
  231. }
  232. /// <summary>
  233. /// Updates a user's password.
  234. /// </summary>
  235. /// <param name="userId">The user id.</param>
  236. /// <param name="request">The <see cref="UpdateUserPassword"/> request.</param>
  237. /// <response code="204">Password successfully reset.</response>
  238. /// <response code="403">User is not allowed to update the password.</response>
  239. /// <response code="404">User not found.</response>
  240. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  241. [HttpPost("{userId}/Password")]
  242. [Authorize(Policy = Policies.DefaultAuthorization)]
  243. [ProducesResponseType(StatusCodes.Status204NoContent)]
  244. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  245. [ProducesResponseType(StatusCodes.Status404NotFound)]
  246. public async Task<ActionResult> UpdateUserPassword(
  247. [FromRoute, Required] Guid userId,
  248. [FromBody, Required] UpdateUserPassword request)
  249. {
  250. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  251. {
  252. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password.");
  253. }
  254. var user = _userManager.GetUserById(userId);
  255. if (user is null)
  256. {
  257. return NotFound("User not found");
  258. }
  259. if (request.ResetPassword)
  260. {
  261. await _userManager.ResetPassword(user).ConfigureAwait(false);
  262. }
  263. else
  264. {
  265. if (!User.IsInRole(UserRoles.Administrator))
  266. {
  267. var success = await _userManager.AuthenticateUser(
  268. user.Username,
  269. request.CurrentPw,
  270. request.CurrentPw,
  271. HttpContext.GetNormalizedRemoteIp().ToString(),
  272. false).ConfigureAwait(false);
  273. if (success is null)
  274. {
  275. return StatusCode(StatusCodes.Status403Forbidden, "Invalid user or password entered.");
  276. }
  277. }
  278. await _userManager.ChangePassword(user, request.NewPw).ConfigureAwait(false);
  279. var currentToken = User.GetToken();
  280. await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
  281. }
  282. return NoContent();
  283. }
  284. /// <summary>
  285. /// Updates a user's easy password.
  286. /// </summary>
  287. /// <param name="userId">The user id.</param>
  288. /// <param name="request">The <see cref="UpdateUserEasyPassword"/> request.</param>
  289. /// <response code="204">Password successfully reset.</response>
  290. /// <response code="403">User is not allowed to update the password.</response>
  291. /// <response code="404">User not found.</response>
  292. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  293. [HttpPost("{userId}/EasyPassword")]
  294. [Authorize(Policy = Policies.DefaultAuthorization)]
  295. [ProducesResponseType(StatusCodes.Status204NoContent)]
  296. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  297. [ProducesResponseType(StatusCodes.Status404NotFound)]
  298. public async Task<ActionResult> UpdateUserEasyPassword(
  299. [FromRoute, Required] Guid userId,
  300. [FromBody, Required] UpdateUserEasyPassword request)
  301. {
  302. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  303. {
  304. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the easy password.");
  305. }
  306. var user = _userManager.GetUserById(userId);
  307. if (user is null)
  308. {
  309. return NotFound("User not found");
  310. }
  311. if (request.ResetPassword)
  312. {
  313. await _userManager.ResetEasyPassword(user).ConfigureAwait(false);
  314. }
  315. else
  316. {
  317. await _userManager.ChangeEasyPassword(user, request.NewPw, request.NewPassword).ConfigureAwait(false);
  318. }
  319. return NoContent();
  320. }
  321. /// <summary>
  322. /// Updates a user.
  323. /// </summary>
  324. /// <param name="userId">The user id.</param>
  325. /// <param name="updateUser">The updated user model.</param>
  326. /// <response code="204">User updated.</response>
  327. /// <response code="400">User information was not supplied.</response>
  328. /// <response code="403">User update forbidden.</response>
  329. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
  330. [HttpPost("{userId}")]
  331. [Authorize(Policy = Policies.DefaultAuthorization)]
  332. [ProducesResponseType(StatusCodes.Status204NoContent)]
  333. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  334. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  335. public async Task<ActionResult> UpdateUser(
  336. [FromRoute, Required] Guid userId,
  337. [FromBody, Required] UserDto updateUser)
  338. {
  339. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  340. {
  341. return StatusCode(StatusCodes.Status403Forbidden, "User update not allowed.");
  342. }
  343. var user = _userManager.GetUserById(userId);
  344. if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
  345. {
  346. await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
  347. }
  348. await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false);
  349. return NoContent();
  350. }
  351. /// <summary>
  352. /// Updates a user policy.
  353. /// </summary>
  354. /// <param name="userId">The user id.</param>
  355. /// <param name="newPolicy">The new user policy.</param>
  356. /// <response code="204">User policy updated.</response>
  357. /// <response code="400">User policy was not supplied.</response>
  358. /// <response code="403">User policy update forbidden.</response>
  359. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure..</returns>
  360. [HttpPost("{userId}/Policy")]
  361. [Authorize(Policy = Policies.RequiresElevation)]
  362. [ProducesResponseType(StatusCodes.Status204NoContent)]
  363. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  364. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  365. public async Task<ActionResult> UpdateUserPolicy(
  366. [FromRoute, Required] Guid userId,
  367. [FromBody, Required] UserPolicy newPolicy)
  368. {
  369. var user = _userManager.GetUserById(userId);
  370. // If removing admin access
  371. if (!newPolicy.IsAdministrator && user.HasPermission(PermissionKind.IsAdministrator))
  372. {
  373. if (_userManager.Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  374. {
  375. return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one user in the system with administrative access.");
  376. }
  377. }
  378. // If disabling
  379. if (newPolicy.IsDisabled && user.HasPermission(PermissionKind.IsAdministrator))
  380. {
  381. return StatusCode(StatusCodes.Status403Forbidden, "Administrators cannot be disabled.");
  382. }
  383. // If disabling
  384. if (newPolicy.IsDisabled && !user.HasPermission(PermissionKind.IsDisabled))
  385. {
  386. if (_userManager.Users.Count(i => !i.HasPermission(PermissionKind.IsDisabled)) == 1)
  387. {
  388. return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one enabled user in the system.");
  389. }
  390. var currentToken = User.GetToken();
  391. await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
  392. }
  393. await _userManager.UpdatePolicyAsync(userId, newPolicy).ConfigureAwait(false);
  394. return NoContent();
  395. }
  396. /// <summary>
  397. /// Updates a user configuration.
  398. /// </summary>
  399. /// <param name="userId">The user id.</param>
  400. /// <param name="userConfig">The new user configuration.</param>
  401. /// <response code="204">User configuration updated.</response>
  402. /// <response code="403">User configuration update forbidden.</response>
  403. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  404. [HttpPost("{userId}/Configuration")]
  405. [Authorize(Policy = Policies.DefaultAuthorization)]
  406. [ProducesResponseType(StatusCodes.Status204NoContent)]
  407. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  408. public async Task<ActionResult> UpdateUserConfiguration(
  409. [FromRoute, Required] Guid userId,
  410. [FromBody, Required] UserConfiguration userConfig)
  411. {
  412. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  413. {
  414. return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed");
  415. }
  416. await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false);
  417. return NoContent();
  418. }
  419. /// <summary>
  420. /// Creates a user.
  421. /// </summary>
  422. /// <param name="request">The create user by name request body.</param>
  423. /// <response code="200">User created.</response>
  424. /// <returns>An <see cref="UserDto"/> of the new user.</returns>
  425. [HttpPost("New")]
  426. [Authorize(Policy = Policies.RequiresElevation)]
  427. [ProducesResponseType(StatusCodes.Status200OK)]
  428. public async Task<ActionResult<UserDto>> CreateUserByName([FromBody, Required] CreateUserByName request)
  429. {
  430. var newUser = await _userManager.CreateUserAsync(request.Name).ConfigureAwait(false);
  431. // no need to authenticate password for new user
  432. if (request.Password is not null)
  433. {
  434. await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false);
  435. }
  436. var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString());
  437. return result;
  438. }
  439. /// <summary>
  440. /// Initiates the forgot password process for a local user.
  441. /// </summary>
  442. /// <param name="forgotPasswordRequest">The forgot password request containing the entered username.</param>
  443. /// <response code="200">Password reset process started.</response>
  444. /// <returns>A <see cref="Task"/> containing a <see cref="ForgotPasswordResult"/>.</returns>
  445. [HttpPost("ForgotPassword")]
  446. [ProducesResponseType(StatusCodes.Status200OK)]
  447. public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
  448. {
  449. var ip = HttpContext.GetNormalizedRemoteIp();
  450. var isLocal = HttpContext.IsLocal()
  451. || _networkManager.IsInLocalNetwork(ip);
  452. if (isLocal)
  453. {
  454. _logger.LogWarning("Password reset process initiated from outside the local network with IP: {IP}", ip);
  455. }
  456. var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);
  457. return result;
  458. }
  459. /// <summary>
  460. /// Redeems a forgot password pin.
  461. /// </summary>
  462. /// <param name="forgotPasswordPinRequest">The forgot password pin request containing the entered pin.</param>
  463. /// <response code="200">Pin reset process started.</response>
  464. /// <returns>A <see cref="Task"/> containing a <see cref="PinRedeemResult"/>.</returns>
  465. [HttpPost("ForgotPassword/Pin")]
  466. [ProducesResponseType(StatusCodes.Status200OK)]
  467. public async Task<ActionResult<PinRedeemResult>> ForgotPasswordPin([FromBody, Required] ForgotPasswordPinDto forgotPasswordPinRequest)
  468. {
  469. var result = await _userManager.RedeemPasswordResetPin(forgotPasswordPinRequest.Pin).ConfigureAwait(false);
  470. return result;
  471. }
  472. /// <summary>
  473. /// Gets the user based on auth token.
  474. /// </summary>
  475. /// <response code="200">User returned.</response>
  476. /// <response code="400">Token is not owned by a user.</response>
  477. /// <returns>A <see cref="UserDto"/> for the authenticated user.</returns>
  478. [HttpGet("Me")]
  479. [Authorize(Policy = Policies.DefaultAuthorization)]
  480. [ProducesResponseType(StatusCodes.Status200OK)]
  481. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  482. public ActionResult<UserDto> GetCurrentUser()
  483. {
  484. var userId = User.GetUserId();
  485. if (userId.Equals(default))
  486. {
  487. return BadRequest();
  488. }
  489. var user = _userManager.GetUserById(userId);
  490. if (user is null)
  491. {
  492. return BadRequest();
  493. }
  494. return _userManager.GetUserDto(user);
  495. }
  496. private IEnumerable<UserDto> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
  497. {
  498. var users = _userManager.Users;
  499. if (isDisabled.HasValue)
  500. {
  501. users = users.Where(i => i.HasPermission(PermissionKind.IsDisabled) == isDisabled.Value);
  502. }
  503. if (isHidden.HasValue)
  504. {
  505. users = users.Where(i => i.HasPermission(PermissionKind.IsHidden) == isHidden.Value);
  506. }
  507. if (filterByDevice)
  508. {
  509. var deviceId = User.GetDeviceId();
  510. if (!string.IsNullOrWhiteSpace(deviceId))
  511. {
  512. users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
  513. }
  514. }
  515. if (filterByNetwork)
  516. {
  517. if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()))
  518. {
  519. users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
  520. }
  521. }
  522. var result = users
  523. .OrderBy(u => u.Username)
  524. .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString()));
  525. return result;
  526. }
  527. }
  528. }