UserController.cs 22 KB

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