UserController.cs 26 KB

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