UserController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. #nullable enable
  2. #pragma warning disable CA1801
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Constants;
  9. using Jellyfin.Api.Helpers;
  10. using Jellyfin.Api.Models.UserDtos;
  11. using Jellyfin.Data.Enums;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller.Authentication;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Devices;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.Net;
  18. using MediaBrowser.Controller.Session;
  19. using MediaBrowser.Model.Configuration;
  20. using MediaBrowser.Model.Dto;
  21. using MediaBrowser.Model.Users;
  22. using Microsoft.AspNetCore.Authorization;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Mvc;
  25. using Microsoft.AspNetCore.Mvc.ModelBinding;
  26. namespace Jellyfin.Api.Controllers
  27. {
  28. /// <summary>
  29. /// User controller.
  30. /// </summary>
  31. [Route("/Users")]
  32. public class UserController : BaseJellyfinApiController
  33. {
  34. private readonly IUserManager _userManager;
  35. private readonly ISessionManager _sessionManager;
  36. private readonly INetworkManager _networkManager;
  37. private readonly IDeviceManager _deviceManager;
  38. private readonly IAuthorizationContext _authContext;
  39. private readonly IServerConfigurationManager _config;
  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. public UserController(
  50. IUserManager userManager,
  51. ISessionManager sessionManager,
  52. INetworkManager networkManager,
  53. IDeviceManager deviceManager,
  54. IAuthorizationContext authContext,
  55. IServerConfigurationManager config)
  56. {
  57. _userManager = userManager;
  58. _sessionManager = sessionManager;
  59. _networkManager = networkManager;
  60. _deviceManager = deviceManager;
  61. _authContext = authContext;
  62. _config = config;
  63. }
  64. /// <summary>
  65. /// Gets a list of users.
  66. /// </summary>
  67. /// <param name="isHidden">Optional filter by IsHidden=true or false.</param>
  68. /// <param name="isDisabled">Optional filter by IsDisabled=true or false.</param>
  69. /// <param name="isGuest">Optional filter by IsGuest=true or false.</param>
  70. /// <response code="200">Users returned.</response>
  71. /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the users.</returns>
  72. [HttpGet]
  73. [Authorize]
  74. [ProducesResponseType(StatusCodes.Status200OK)]
  75. public ActionResult<IEnumerable<UserDto>> GetUsers(
  76. [FromQuery] bool? isHidden,
  77. [FromQuery] bool? isDisabled,
  78. [FromQuery] bool? isGuest)
  79. {
  80. var users = Get(isHidden, isDisabled, false, false);
  81. return Ok(users);
  82. }
  83. /// <summary>
  84. /// Gets a list of publicly visible users for display on a login screen.
  85. /// </summary>
  86. /// <response code="200">Public users returned.</response>
  87. /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the public users.</returns>
  88. [HttpGet("Public")]
  89. [ProducesResponseType(StatusCodes.Status200OK)]
  90. public ActionResult<IEnumerable<UserDto>> GetPublicUsers()
  91. {
  92. // If the startup wizard hasn't been completed then just return all users
  93. if (!_config.Configuration.IsStartupWizardCompleted)
  94. {
  95. return Ok(GetUsers(false, false, false).Value);
  96. }
  97. return Ok(Get(false, false, true, true));
  98. }
  99. /// <summary>
  100. /// Gets a user by Id.
  101. /// </summary>
  102. /// <param name="id">The user id.</param>
  103. /// <response code="200">User returned.</response>
  104. /// <response code="404">User not found.</response>
  105. /// <returns>An <see cref="UserDto"/> with information about the user or a <see cref="NotFoundResult"/> if the user was not found.</returns>
  106. [HttpGet("{id}")]
  107. // TODO: authorize escapeParentalControl
  108. [Authorize]
  109. [ProducesResponseType(StatusCodes.Status200OK)]
  110. [ProducesResponseType(StatusCodes.Status404NotFound)]
  111. public ActionResult<UserDto> GetUserById([FromRoute] Guid id)
  112. {
  113. var user = _userManager.GetUserById(id);
  114. if (user == null)
  115. {
  116. return NotFound("User not found");
  117. }
  118. var result = _userManager.GetUserDto(user, HttpContext.Connection.RemoteIpAddress.ToString());
  119. return Ok(result);
  120. }
  121. /// <summary>
  122. /// Deletes a user.
  123. /// </summary>
  124. /// <param name="id">The user id.</param>
  125. /// <response code="200">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("{id}")]
  129. [Authorize(Policy = Policies.RequiresElevation)]
  130. [ProducesResponseType(StatusCodes.Status204NoContent)]
  131. [ProducesResponseType(StatusCodes.Status404NotFound)]
  132. public ActionResult DeleteUser([FromRoute] Guid id)
  133. {
  134. var user = _userManager.GetUserById(id);
  135. if (user == null)
  136. {
  137. return NotFound("User not found");
  138. }
  139. _sessionManager.RevokeUserTokens(user.Id, null);
  140. _userManager.DeleteUser(user);
  141. return NoContent();
  142. }
  143. /// <summary>
  144. /// Authenticates a user.
  145. /// </summary>
  146. /// <param name="id">The user id.</param>
  147. /// <param name="pw">The password as plain text.</param>
  148. /// <param name="password">The password sha1-hash.</param>
  149. /// <response code="200">User authenticated.</response>
  150. /// <response code="403">Sha1-hashed password only is not allowed.</response>
  151. /// <response code="404">User not found.</response>
  152. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationResult"/>.</returns>
  153. [HttpPost("{id}/Authenticate")]
  154. [ProducesResponseType(StatusCodes.Status200OK)]
  155. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  156. [ProducesResponseType(StatusCodes.Status404NotFound)]
  157. public async Task<ActionResult<AuthenticationResult>> AuthenticateUser(
  158. [FromRoute, Required] Guid id,
  159. [FromQuery, BindRequired] string pw,
  160. [FromQuery, BindRequired] string password)
  161. {
  162. var user = _userManager.GetUserById(id);
  163. if (user == null)
  164. {
  165. return NotFound("User not found");
  166. }
  167. if (!string.IsNullOrEmpty(password) && string.IsNullOrEmpty(pw))
  168. {
  169. return Forbid("Only sha1 password is not allowed.");
  170. }
  171. // Password should always be null
  172. return await AuthenticateUserByName(user.Username, pw, password).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, BindRequired] AuthenticateUserByName request)
  183. {
  184. var auth = _authContext.GetAuthorizationInfo(Request);
  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. PasswordSha1 = request.Password,
  195. RemoteEndPoint = HttpContext.Connection.RemoteIpAddress.ToString(),
  196. Username = request.Username
  197. }).ConfigureAwait(false);
  198. return Ok(result);
  199. }
  200. catch (SecurityException e)
  201. {
  202. // rethrow adding IP address to message
  203. throw new SecurityException($"[{HttpContext.Connection.RemoteIpAddress}] {e.Message}", e);
  204. }
  205. }
  206. /// <summary>
  207. /// Updates a user's password.
  208. /// </summary>
  209. /// <param name="id">The user id.</param>
  210. /// <param name="currentPassword">The current password sha1-hash.</param>
  211. /// <param name="currentPw">The current password as plain text.</param>
  212. /// <param name="newPw">The new password in plain text.</param>
  213. /// <param name="resetPassword">Whether to reset the password.</param>
  214. /// <response code="200">Password successfully reset.</response>
  215. /// <response code="403">User is not allowed to update the password.</response>
  216. /// <response code="404">User not found.</response>
  217. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  218. [HttpPost("{id}/Password")]
  219. [Authorize]
  220. [ProducesResponseType(StatusCodes.Status204NoContent)]
  221. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  222. [ProducesResponseType(StatusCodes.Status404NotFound)]
  223. public async Task<ActionResult> UpdateUserPassword(
  224. [FromRoute] Guid id,
  225. [FromBody] string currentPassword,
  226. [FromBody] string currentPw,
  227. [FromBody] string newPw,
  228. [FromBody] bool resetPassword)
  229. {
  230. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, id, true))
  231. {
  232. return Forbid("User is not allowed to update the password.");
  233. }
  234. var user = _userManager.GetUserById(id);
  235. if (user == null)
  236. {
  237. return NotFound("User not found");
  238. }
  239. if (resetPassword)
  240. {
  241. await _userManager.ResetPassword(user).ConfigureAwait(false);
  242. }
  243. else
  244. {
  245. var success = await _userManager.AuthenticateUser(
  246. user.Username,
  247. currentPw,
  248. currentPassword,
  249. HttpContext.Connection.RemoteIpAddress.ToString(),
  250. false).ConfigureAwait(false);
  251. if (success == null)
  252. {
  253. return Forbid("Invalid user or password entered.");
  254. }
  255. await _userManager.ChangePassword(user, newPw).ConfigureAwait(false);
  256. var currentToken = _authContext.GetAuthorizationInfo(Request).Token;
  257. _sessionManager.RevokeUserTokens(user.Id, currentToken);
  258. }
  259. return NoContent();
  260. }
  261. /// <summary>
  262. /// Updates a user's easy password.
  263. /// </summary>
  264. /// <param name="id">The user id.</param>
  265. /// <param name="newPassword">The new password sha1-hash.</param>
  266. /// <param name="newPw">The new password in plain text.</param>
  267. /// <param name="resetPassword">Whether to reset the password.</param>
  268. /// <response code="200">Password successfully reset.</response>
  269. /// <response code="403">User is not allowed to update the password.</response>
  270. /// <response code="404">User not found.</response>
  271. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  272. [HttpPost("{id}/EasyPassword")]
  273. [Authorize]
  274. [ProducesResponseType(StatusCodes.Status204NoContent)]
  275. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  276. [ProducesResponseType(StatusCodes.Status404NotFound)]
  277. public ActionResult UpdateUserEasyPassword(
  278. [FromRoute] Guid id,
  279. [FromBody] string newPassword,
  280. [FromBody] string newPw,
  281. [FromBody] bool resetPassword)
  282. {
  283. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, id, true))
  284. {
  285. return Forbid("User is not allowed to update the easy password.");
  286. }
  287. var user = _userManager.GetUserById(id);
  288. if (user == null)
  289. {
  290. return NotFound("User not found");
  291. }
  292. if (resetPassword)
  293. {
  294. _userManager.ResetEasyPassword(user);
  295. }
  296. else
  297. {
  298. _userManager.ChangeEasyPassword(user, newPw, newPassword);
  299. }
  300. return NoContent();
  301. }
  302. /// <summary>
  303. /// Updates a user.
  304. /// </summary>
  305. /// <param name="id">The user id.</param>
  306. /// <param name="updateUser">The updated user model.</param>
  307. /// <response code="204">User updated.</response>
  308. /// <response code="400">User information was not supplied.</response>
  309. /// <response code="403">User update forbidden.</response>
  310. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
  311. [HttpPost("{id}")]
  312. [Authorize]
  313. [ProducesResponseType(StatusCodes.Status204NoContent)]
  314. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  315. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  316. public async Task<ActionResult> UpdateUser(
  317. [FromRoute] Guid id,
  318. [FromBody] UserDto updateUser)
  319. {
  320. if (updateUser == null)
  321. {
  322. return BadRequest();
  323. }
  324. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, id, false))
  325. {
  326. return Forbid("User update not allowed.");
  327. }
  328. var user = _userManager.GetUserById(id);
  329. if (string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
  330. {
  331. await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
  332. _userManager.UpdateConfiguration(user.Id, updateUser.Configuration);
  333. }
  334. else
  335. {
  336. await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
  337. _userManager.UpdateConfiguration(updateUser.Id, updateUser.Configuration);
  338. }
  339. return NoContent();
  340. }
  341. /// <summary>
  342. /// Updates a user policy.
  343. /// </summary>
  344. /// <param name="id">The user id.</param>
  345. /// <param name="newPolicy">The new user policy.</param>
  346. /// <response code="204">User policy updated.</response>
  347. /// <response code="400">User policy was not supplied.</response>
  348. /// <response code="403">User policy update forbidden.</response>
  349. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure..</returns>
  350. [HttpPost("{id}/Policy")]
  351. [Authorize]
  352. [ProducesResponseType(StatusCodes.Status204NoContent)]
  353. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  354. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  355. public ActionResult UpdateUserPolicy(
  356. [FromRoute] Guid id,
  357. [FromBody] UserPolicy newPolicy)
  358. {
  359. if (newPolicy == null)
  360. {
  361. return BadRequest();
  362. }
  363. var user = _userManager.GetUserById(id);
  364. // If removing admin access
  365. if (!(newPolicy.IsAdministrator && user.HasPermission(PermissionKind.IsAdministrator)))
  366. {
  367. if (_userManager.Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  368. {
  369. return Forbid("There must be at least one user in the system with administrative access.");
  370. }
  371. }
  372. // If disabling
  373. if (newPolicy.IsDisabled && user.HasPermission(PermissionKind.IsAdministrator))
  374. {
  375. return Forbid("Administrators cannot be disabled.");
  376. }
  377. // If disabling
  378. if (newPolicy.IsDisabled && !user.HasPermission(PermissionKind.IsDisabled))
  379. {
  380. if (_userManager.Users.Count(i => !i.HasPermission(PermissionKind.IsDisabled)) == 1)
  381. {
  382. return Forbid("There must be at least one enabled user in the system.");
  383. }
  384. var currentToken = _authContext.GetAuthorizationInfo(Request).Token;
  385. _sessionManager.RevokeUserTokens(user.Id, currentToken);
  386. }
  387. _userManager.UpdatePolicy(id, newPolicy);
  388. return NoContent();
  389. }
  390. /// <summary>
  391. /// Updates a user configuration.
  392. /// </summary>
  393. /// <param name="id">The user id.</param>
  394. /// <param name="userConfig">The new user configuration.</param>
  395. /// <response code="204">User configuration updated.</response>
  396. /// <response code="403">User configuration update forbidden.</response>
  397. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  398. [HttpPost("{id}/Configuration")]
  399. [Authorize]
  400. [ProducesResponseType(StatusCodes.Status204NoContent)]
  401. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  402. public ActionResult UpdateUserConfiguration(
  403. [FromRoute] Guid id,
  404. [FromBody] UserConfiguration userConfig)
  405. {
  406. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, id, false))
  407. {
  408. return Forbid("User configuration update not allowed");
  409. }
  410. _userManager.UpdateConfiguration(id, userConfig);
  411. return NoContent();
  412. }
  413. /// <summary>
  414. /// Creates a user.
  415. /// </summary>
  416. /// <param name="name">The username.</param>
  417. /// <param name="password">The password.</param>
  418. /// <response code="200">User created.</response>
  419. /// <returns>An <see cref="UserDto"/> of the new user.</returns>
  420. [HttpPost("/Users/New")]
  421. [Authorize(Policy = Policies.RequiresElevation)]
  422. [ProducesResponseType(StatusCodes.Status200OK)]
  423. public async Task<ActionResult<UserDto>> CreateUserByName(
  424. [FromBody] string name,
  425. [FromBody] string password)
  426. {
  427. var newUser = _userManager.CreateUser(name);
  428. // no need to authenticate password for new user
  429. if (password != null)
  430. {
  431. await _userManager.ChangePassword(newUser, password).ConfigureAwait(false);
  432. }
  433. var result = _userManager.GetUserDto(newUser, HttpContext.Connection.RemoteIpAddress.ToString());
  434. return Ok(result);
  435. }
  436. /// <summary>
  437. /// Initiates the forgot password process for a local user.
  438. /// </summary>
  439. /// <param name="enteredUsername">The entered username.</param>
  440. /// <response code="200">Password reset process started.</response>
  441. /// <returns>A <see cref="Task"/> containing a <see cref="ForgotPasswordResult"/>.</returns>
  442. [HttpPost("ForgotPassword")]
  443. [ProducesResponseType(StatusCodes.Status200OK)]
  444. public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody] string enteredUsername)
  445. {
  446. var isLocal = HttpContext.Connection.RemoteIpAddress.Equals(HttpContext.Connection.LocalIpAddress)
  447. || _networkManager.IsInLocalNetwork(HttpContext.Connection.RemoteIpAddress.ToString());
  448. var result = await _userManager.StartForgotPasswordProcess(enteredUsername, isLocal).ConfigureAwait(false);
  449. return Ok(result);
  450. }
  451. /// <summary>
  452. /// Redeems a forgot password pin.
  453. /// </summary>
  454. /// <param name="pin">The pin.</param>
  455. /// <response code="200">Pin reset process started.</response>
  456. /// <returns>A <see cref="Task"/> containing a <see cref="PinRedeemResult"/>.</returns>
  457. [HttpPost("ForgotPassword/Pin")]
  458. [ProducesResponseType(StatusCodes.Status200OK)]
  459. public async Task<ActionResult<PinRedeemResult>> ForgotPasswordPin([FromBody] string pin)
  460. {
  461. var result = await _userManager.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  462. return Ok(result);
  463. }
  464. private IEnumerable<UserDto> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
  465. {
  466. var users = _userManager.Users;
  467. if (isDisabled.HasValue)
  468. {
  469. users = users.Where(i => i.HasPermission(PermissionKind.IsDisabled) == isDisabled.Value);
  470. }
  471. if (isHidden.HasValue)
  472. {
  473. users = users.Where(i => i.HasPermission(PermissionKind.IsHidden) == isHidden.Value);
  474. }
  475. if (filterByDevice)
  476. {
  477. var deviceId = _authContext.GetAuthorizationInfo(Request).DeviceId;
  478. if (!string.IsNullOrWhiteSpace(deviceId))
  479. {
  480. users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
  481. }
  482. }
  483. if (filterByNetwork)
  484. {
  485. if (!_networkManager.IsInLocalNetwork(HttpContext.Connection.RemoteIpAddress.ToString()))
  486. {
  487. users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
  488. }
  489. }
  490. var result = users
  491. .OrderBy(u => u.Username)
  492. .Select(i => _userManager.GetUserDto(i, HttpContext.Connection.RemoteIpAddress.ToString()))
  493. .ToArray();
  494. return result;
  495. }
  496. }
  497. }