UserController.cs 22 KB

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