UserController.cs 26 KB

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