UserController.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
  259. {
  260. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password.");
  261. }
  262. var user = _userManager.GetUserById(requestUserId);
  263. if (user is null)
  264. {
  265. return NotFound("User not found");
  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. 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(_userManager, User, requestUserId, 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(user.Id, 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. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
  456. {
  457. return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed");
  458. }
  459. await _userManager.UpdateConfigurationAsync(requestUserId, userConfig).ConfigureAwait(false);
  460. return NoContent();
  461. }
  462. /// <summary>
  463. /// Updates a user configuration.
  464. /// </summary>
  465. /// <param name="userId">The user id.</param>
  466. /// <param name="userConfig">The new user configuration.</param>
  467. /// <response code="204">User configuration updated.</response>
  468. /// <response code="403">User configuration update forbidden.</response>
  469. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  470. [HttpPost("{userId}/Configuration")]
  471. [Authorize]
  472. [Obsolete("Kept for backwards compatibility")]
  473. [ApiExplorerSettings(IgnoreApi = true)]
  474. [ProducesResponseType(StatusCodes.Status204NoContent)]
  475. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  476. public Task<ActionResult> UpdateUserConfigurationLegacy(
  477. [FromRoute, Required] Guid userId,
  478. [FromBody, Required] UserConfiguration userConfig)
  479. => UpdateUserConfiguration(userId, userConfig);
  480. /// <summary>
  481. /// Creates a user.
  482. /// </summary>
  483. /// <param name="request">The create user by name request body.</param>
  484. /// <response code="200">User created.</response>
  485. /// <returns>An <see cref="UserDto"/> of the new user.</returns>
  486. [HttpPost("New")]
  487. [Authorize(Policy = Policies.RequiresElevation)]
  488. [ProducesResponseType(StatusCodes.Status200OK)]
  489. public async Task<ActionResult<UserDto>> CreateUserByName([FromBody, Required] CreateUserByName request)
  490. {
  491. var newUser = await _userManager.CreateUserAsync(request.Name).ConfigureAwait(false);
  492. // no need to authenticate password for new user
  493. if (request.Password is not null)
  494. {
  495. await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false);
  496. }
  497. var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIP().ToString());
  498. return result;
  499. }
  500. /// <summary>
  501. /// Initiates the forgot password process for a local user.
  502. /// </summary>
  503. /// <param name="forgotPasswordRequest">The forgot password request containing the entered username.</param>
  504. /// <response code="200">Password reset process started.</response>
  505. /// <returns>A <see cref="Task"/> containing a <see cref="ForgotPasswordResult"/>.</returns>
  506. [HttpPost("ForgotPassword")]
  507. [ProducesResponseType(StatusCodes.Status200OK)]
  508. public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
  509. {
  510. var ip = HttpContext.GetNormalizedRemoteIP();
  511. var isLocal = HttpContext.IsLocal()
  512. || _networkManager.IsInLocalNetwork(ip);
  513. if (!isLocal)
  514. {
  515. _logger.LogWarning("Password reset process initiated from outside the local network with IP: {IP}", ip);
  516. }
  517. var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);
  518. return result;
  519. }
  520. /// <summary>
  521. /// Redeems a forgot password pin.
  522. /// </summary>
  523. /// <param name="forgotPasswordPinRequest">The forgot password pin request containing the entered pin.</param>
  524. /// <response code="200">Pin reset process started.</response>
  525. /// <returns>A <see cref="Task"/> containing a <see cref="PinRedeemResult"/>.</returns>
  526. [HttpPost("ForgotPassword/Pin")]
  527. [ProducesResponseType(StatusCodes.Status200OK)]
  528. public async Task<ActionResult<PinRedeemResult>> ForgotPasswordPin([FromBody, Required] ForgotPasswordPinDto forgotPasswordPinRequest)
  529. {
  530. var result = await _userManager.RedeemPasswordResetPin(forgotPasswordPinRequest.Pin).ConfigureAwait(false);
  531. return result;
  532. }
  533. /// <summary>
  534. /// Gets the user based on auth token.
  535. /// </summary>
  536. /// <response code="200">User returned.</response>
  537. /// <response code="400">Token is not owned by a user.</response>
  538. /// <returns>A <see cref="UserDto"/> for the authenticated user.</returns>
  539. [HttpGet("Me")]
  540. [Authorize]
  541. [ProducesResponseType(StatusCodes.Status200OK)]
  542. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  543. public ActionResult<UserDto> GetCurrentUser()
  544. {
  545. var userId = User.GetUserId();
  546. if (userId.IsEmpty())
  547. {
  548. return BadRequest();
  549. }
  550. var user = _userManager.GetUserById(userId);
  551. if (user is null)
  552. {
  553. return BadRequest();
  554. }
  555. return _userManager.GetUserDto(user);
  556. }
  557. private IEnumerable<UserDto> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
  558. {
  559. var users = _userManager.Users;
  560. if (isDisabled.HasValue)
  561. {
  562. users = users.Where(i => i.HasPermission(PermissionKind.IsDisabled) == isDisabled.Value);
  563. }
  564. if (isHidden.HasValue)
  565. {
  566. users = users.Where(i => i.HasPermission(PermissionKind.IsHidden) == isHidden.Value);
  567. }
  568. if (filterByDevice)
  569. {
  570. var deviceId = User.GetDeviceId();
  571. if (!string.IsNullOrWhiteSpace(deviceId))
  572. {
  573. users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
  574. }
  575. }
  576. if (filterByNetwork)
  577. {
  578. if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP()))
  579. {
  580. users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
  581. }
  582. }
  583. var result = users
  584. .OrderBy(u => u.Username)
  585. .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIP().ToString()));
  586. return result;
  587. }
  588. }