UserController.cs 23 KB

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