UserController.cs 23 KB

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