UserController.cs 24 KB

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