UserController.cs 25 KB

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