UserController.cs 23 KB

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