UserController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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]
  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. if (user is null)
  141. {
  142. return NotFound();
  143. }
  144. await _sessionManager.RevokeUserTokens(user.Id, null).ConfigureAwait(false);
  145. await _userManager.DeleteUserAsync(userId).ConfigureAwait(false);
  146. return NoContent();
  147. }
  148. /// <summary>
  149. /// Authenticates a user.
  150. /// </summary>
  151. /// <param name="userId">The user id.</param>
  152. /// <param name="pw">The password as plain text.</param>
  153. /// <response code="200">User authenticated.</response>
  154. /// <response code="403">Sha1-hashed password only is not allowed.</response>
  155. /// <response code="404">User not found.</response>
  156. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationResult"/>.</returns>
  157. [HttpPost("{userId}/Authenticate")]
  158. [ProducesResponseType(StatusCodes.Status200OK)]
  159. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  160. [ProducesResponseType(StatusCodes.Status404NotFound)]
  161. [Obsolete("Authenticate with username instead")]
  162. public async Task<ActionResult<AuthenticationResult>> AuthenticateUser(
  163. [FromRoute, Required] Guid userId,
  164. [FromQuery, Required] string pw)
  165. {
  166. var user = _userManager.GetUserById(userId);
  167. if (user is null)
  168. {
  169. return NotFound("User not found");
  170. }
  171. AuthenticateUserByName request = new AuthenticateUserByName
  172. {
  173. Username = user.Username,
  174. Pw = pw
  175. };
  176. return await AuthenticateUserByName(request).ConfigureAwait(false);
  177. }
  178. /// <summary>
  179. /// Authenticates a user by name.
  180. /// </summary>
  181. /// <param name="request">The <see cref="AuthenticateUserByName"/> request.</param>
  182. /// <response code="200">User authenticated.</response>
  183. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
  184. [HttpPost("AuthenticateByName")]
  185. [ProducesResponseType(StatusCodes.Status200OK)]
  186. public async Task<ActionResult<AuthenticationResult>> AuthenticateUserByName([FromBody, Required] AuthenticateUserByName request)
  187. {
  188. var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
  189. try
  190. {
  191. var result = await _sessionManager.AuthenticateNewSession(new AuthenticationRequest
  192. {
  193. App = auth.Client,
  194. AppVersion = auth.Version,
  195. DeviceId = auth.DeviceId,
  196. DeviceName = auth.Device,
  197. Password = request.Pw,
  198. RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(),
  199. Username = request.Username
  200. }).ConfigureAwait(false);
  201. return result;
  202. }
  203. catch (SecurityException e)
  204. {
  205. // rethrow adding IP address to message
  206. throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
  207. }
  208. }
  209. /// <summary>
  210. /// Authenticates a user with quick connect.
  211. /// </summary>
  212. /// <param name="request">The <see cref="QuickConnectDto"/> request.</param>
  213. /// <response code="200">User authenticated.</response>
  214. /// <response code="400">Missing token.</response>
  215. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
  216. [HttpPost("AuthenticateWithQuickConnect")]
  217. [ProducesResponseType(StatusCodes.Status200OK)]
  218. public ActionResult<AuthenticationResult> AuthenticateWithQuickConnect([FromBody, Required] QuickConnectDto request)
  219. {
  220. try
  221. {
  222. return _quickConnectManager.GetAuthorizedRequest(request.Secret);
  223. }
  224. catch (SecurityException e)
  225. {
  226. // rethrow adding IP address to message
  227. throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
  228. }
  229. }
  230. /// <summary>
  231. /// Updates a user's password.
  232. /// </summary>
  233. /// <param name="userId">The user id.</param>
  234. /// <param name="request">The <see cref="UpdateUserPassword"/> request.</param>
  235. /// <response code="204">Password successfully reset.</response>
  236. /// <response code="403">User is not allowed to update the password.</response>
  237. /// <response code="404">User not found.</response>
  238. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  239. [HttpPost("{userId}/Password")]
  240. [Authorize]
  241. [ProducesResponseType(StatusCodes.Status204NoContent)]
  242. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  243. [ProducesResponseType(StatusCodes.Status404NotFound)]
  244. public async Task<ActionResult> UpdateUserPassword(
  245. [FromRoute, Required] Guid userId,
  246. [FromBody, Required] UpdateUserPassword request)
  247. {
  248. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  249. {
  250. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password.");
  251. }
  252. var user = _userManager.GetUserById(userId);
  253. if (user is null)
  254. {
  255. return NotFound("User not found");
  256. }
  257. if (request.ResetPassword)
  258. {
  259. await _userManager.ResetPassword(user).ConfigureAwait(false);
  260. }
  261. else
  262. {
  263. if (!User.IsInRole(UserRoles.Administrator) || User.GetUserId().Equals(userId))
  264. {
  265. var success = await _userManager.AuthenticateUser(
  266. user.Username,
  267. request.CurrentPw ?? string.Empty,
  268. request.CurrentPw ?? string.Empty,
  269. HttpContext.GetNormalizedRemoteIp().ToString(),
  270. false).ConfigureAwait(false);
  271. if (success is null)
  272. {
  273. return StatusCode(StatusCodes.Status403Forbidden, "Invalid user or password entered.");
  274. }
  275. }
  276. await _userManager.ChangePassword(user, request.NewPw ?? string.Empty).ConfigureAwait(false);
  277. var currentToken = User.GetToken();
  278. await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
  279. }
  280. return NoContent();
  281. }
  282. /// <summary>
  283. /// Updates a user's easy password.
  284. /// </summary>
  285. /// <param name="userId">The user id.</param>
  286. /// <param name="request">The <see cref="UpdateUserEasyPassword"/> request.</param>
  287. /// <response code="204">Password successfully reset.</response>
  288. /// <response code="403">User is not allowed to update the password.</response>
  289. /// <response code="404">User not found.</response>
  290. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  291. [HttpPost("{userId}/EasyPassword")]
  292. [Authorize]
  293. [ProducesResponseType(StatusCodes.Status204NoContent)]
  294. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  295. [ProducesResponseType(StatusCodes.Status404NotFound)]
  296. public async Task<ActionResult> UpdateUserEasyPassword(
  297. [FromRoute, Required] Guid userId,
  298. [FromBody, Required] UpdateUserEasyPassword request)
  299. {
  300. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  301. {
  302. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the easy password.");
  303. }
  304. var user = _userManager.GetUserById(userId);
  305. if (user is null)
  306. {
  307. return NotFound("User not found");
  308. }
  309. if (request.ResetPassword)
  310. {
  311. await _userManager.ResetEasyPassword(user).ConfigureAwait(false);
  312. }
  313. else
  314. {
  315. await _userManager.ChangeEasyPassword(user, request.NewPw ?? string.Empty, request.NewPassword ?? string.Empty).ConfigureAwait(false);
  316. }
  317. return NoContent();
  318. }
  319. /// <summary>
  320. /// Updates a user.
  321. /// </summary>
  322. /// <param name="userId">The user id.</param>
  323. /// <param name="updateUser">The updated user model.</param>
  324. /// <response code="204">User updated.</response>
  325. /// <response code="400">User information was not supplied.</response>
  326. /// <response code="403">User update forbidden.</response>
  327. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
  328. [HttpPost("{userId}")]
  329. [Authorize]
  330. [ProducesResponseType(StatusCodes.Status204NoContent)]
  331. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  332. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  333. public async Task<ActionResult> UpdateUser(
  334. [FromRoute, Required] Guid userId,
  335. [FromBody, Required] UserDto updateUser)
  336. {
  337. var user = _userManager.GetUserById(userId);
  338. if (user is null)
  339. {
  340. return NotFound();
  341. }
  342. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  343. {
  344. return StatusCode(StatusCodes.Status403Forbidden, "User update not allowed.");
  345. }
  346. if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
  347. {
  348. await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
  349. }
  350. await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false);
  351. return NoContent();
  352. }
  353. /// <summary>
  354. /// Updates a user policy.
  355. /// </summary>
  356. /// <param name="userId">The user id.</param>
  357. /// <param name="newPolicy">The new user policy.</param>
  358. /// <response code="204">User policy updated.</response>
  359. /// <response code="400">User policy was not supplied.</response>
  360. /// <response code="403">User policy update forbidden.</response>
  361. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure..</returns>
  362. [HttpPost("{userId}/Policy")]
  363. [Authorize(Policy = Policies.RequiresElevation)]
  364. [ProducesResponseType(StatusCodes.Status204NoContent)]
  365. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  366. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  367. public async Task<ActionResult> UpdateUserPolicy(
  368. [FromRoute, Required] Guid userId,
  369. [FromBody, Required] UserPolicy newPolicy)
  370. {
  371. var user = _userManager.GetUserById(userId);
  372. if (user is null)
  373. {
  374. return NotFound();
  375. }
  376. // If removing admin access
  377. if (!newPolicy.IsAdministrator && user.HasPermission(PermissionKind.IsAdministrator))
  378. {
  379. if (_userManager.Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  380. {
  381. return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one user in the system with administrative access.");
  382. }
  383. }
  384. // If disabling
  385. if (newPolicy.IsDisabled && user.HasPermission(PermissionKind.IsAdministrator))
  386. {
  387. return StatusCode(StatusCodes.Status403Forbidden, "Administrators cannot be disabled.");
  388. }
  389. // If disabling
  390. if (newPolicy.IsDisabled && !user.HasPermission(PermissionKind.IsDisabled))
  391. {
  392. if (_userManager.Users.Count(i => !i.HasPermission(PermissionKind.IsDisabled)) == 1)
  393. {
  394. return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one enabled user in the system.");
  395. }
  396. var currentToken = User.GetToken();
  397. await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
  398. }
  399. await _userManager.UpdatePolicyAsync(userId, newPolicy).ConfigureAwait(false);
  400. return NoContent();
  401. }
  402. /// <summary>
  403. /// Updates a user configuration.
  404. /// </summary>
  405. /// <param name="userId">The user id.</param>
  406. /// <param name="userConfig">The new user configuration.</param>
  407. /// <response code="204">User configuration updated.</response>
  408. /// <response code="403">User configuration update forbidden.</response>
  409. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  410. [HttpPost("{userId}/Configuration")]
  411. [Authorize]
  412. [ProducesResponseType(StatusCodes.Status204NoContent)]
  413. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  414. public async Task<ActionResult> UpdateUserConfiguration(
  415. [FromRoute, Required] Guid userId,
  416. [FromBody, Required] UserConfiguration userConfig)
  417. {
  418. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
  419. {
  420. return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed");
  421. }
  422. await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false);
  423. return NoContent();
  424. }
  425. /// <summary>
  426. /// Creates a user.
  427. /// </summary>
  428. /// <param name="request">The create user by name request body.</param>
  429. /// <response code="200">User created.</response>
  430. /// <returns>An <see cref="UserDto"/> of the new user.</returns>
  431. [HttpPost("New")]
  432. [Authorize(Policy = Policies.RequiresElevation)]
  433. [ProducesResponseType(StatusCodes.Status200OK)]
  434. public async Task<ActionResult<UserDto>> CreateUserByName([FromBody, Required] CreateUserByName request)
  435. {
  436. var newUser = await _userManager.CreateUserAsync(request.Name).ConfigureAwait(false);
  437. // no need to authenticate password for new user
  438. if (request.Password is not null)
  439. {
  440. await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false);
  441. }
  442. var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString());
  443. return result;
  444. }
  445. /// <summary>
  446. /// Initiates the forgot password process for a local user.
  447. /// </summary>
  448. /// <param name="forgotPasswordRequest">The forgot password request containing the entered username.</param>
  449. /// <response code="200">Password reset process started.</response>
  450. /// <returns>A <see cref="Task"/> containing a <see cref="ForgotPasswordResult"/>.</returns>
  451. [HttpPost("ForgotPassword")]
  452. [ProducesResponseType(StatusCodes.Status200OK)]
  453. public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
  454. {
  455. var ip = HttpContext.GetNormalizedRemoteIp();
  456. var isLocal = HttpContext.IsLocal()
  457. || _networkManager.IsInLocalNetwork(ip);
  458. if (isLocal)
  459. {
  460. _logger.LogWarning("Password reset process initiated from outside the local network with IP: {IP}", ip);
  461. }
  462. var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);
  463. return result;
  464. }
  465. /// <summary>
  466. /// Redeems a forgot password pin.
  467. /// </summary>
  468. /// <param name="forgotPasswordPinRequest">The forgot password pin request containing the entered pin.</param>
  469. /// <response code="200">Pin reset process started.</response>
  470. /// <returns>A <see cref="Task"/> containing a <see cref="PinRedeemResult"/>.</returns>
  471. [HttpPost("ForgotPassword/Pin")]
  472. [ProducesResponseType(StatusCodes.Status200OK)]
  473. public async Task<ActionResult<PinRedeemResult>> ForgotPasswordPin([FromBody, Required] ForgotPasswordPinDto forgotPasswordPinRequest)
  474. {
  475. var result = await _userManager.RedeemPasswordResetPin(forgotPasswordPinRequest.Pin).ConfigureAwait(false);
  476. return result;
  477. }
  478. /// <summary>
  479. /// Gets the user based on auth token.
  480. /// </summary>
  481. /// <response code="200">User returned.</response>
  482. /// <response code="400">Token is not owned by a user.</response>
  483. /// <returns>A <see cref="UserDto"/> for the authenticated user.</returns>
  484. [HttpGet("Me")]
  485. [Authorize]
  486. [ProducesResponseType(StatusCodes.Status200OK)]
  487. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  488. public ActionResult<UserDto> GetCurrentUser()
  489. {
  490. var userId = User.GetUserId();
  491. if (userId.Equals(default))
  492. {
  493. return BadRequest();
  494. }
  495. var user = _userManager.GetUserById(userId);
  496. if (user is null)
  497. {
  498. return BadRequest();
  499. }
  500. return _userManager.GetUserDto(user);
  501. }
  502. private IEnumerable<UserDto> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
  503. {
  504. var users = _userManager.Users;
  505. if (isDisabled.HasValue)
  506. {
  507. users = users.Where(i => i.HasPermission(PermissionKind.IsDisabled) == isDisabled.Value);
  508. }
  509. if (isHidden.HasValue)
  510. {
  511. users = users.Where(i => i.HasPermission(PermissionKind.IsHidden) == isHidden.Value);
  512. }
  513. if (filterByDevice)
  514. {
  515. var deviceId = User.GetDeviceId();
  516. if (!string.IsNullOrWhiteSpace(deviceId))
  517. {
  518. users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
  519. }
  520. }
  521. if (filterByNetwork)
  522. {
  523. if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()))
  524. {
  525. users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
  526. }
  527. }
  528. var result = users
  529. .OrderBy(u => u.Username)
  530. .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString()));
  531. return result;
  532. }
  533. }