UserController.cs 26 KB

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