UserController.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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.Extensions;
  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.Extensions.Logging;
  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. private readonly ILogger _logger;
  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. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  50. public UserController(
  51. IUserManager userManager,
  52. ISessionManager sessionManager,
  53. INetworkManager networkManager,
  54. IDeviceManager deviceManager,
  55. IAuthorizationContext authContext,
  56. IServerConfigurationManager config,
  57. ILogger<UserController> logger)
  58. {
  59. _userManager = userManager;
  60. _sessionManager = sessionManager;
  61. _networkManager = networkManager;
  62. _deviceManager = deviceManager;
  63. _authContext = authContext;
  64. _config = config;
  65. _logger = logger;
  66. }
  67. /// <summary>
  68. /// Gets a list of users.
  69. /// </summary>
  70. /// <param name="isHidden">Optional filter by IsHidden=true or false.</param>
  71. /// <param name="isDisabled">Optional filter by IsDisabled=true or false.</param>
  72. /// <response code="200">Users returned.</response>
  73. /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the users.</returns>
  74. [HttpGet]
  75. [Authorize(Policy = Policies.DefaultAuthorization)]
  76. [ProducesResponseType(StatusCodes.Status200OK)]
  77. public ActionResult<IEnumerable<UserDto>> GetUsers(
  78. [FromQuery] bool? isHidden,
  79. [FromQuery] bool? isDisabled)
  80. {
  81. var users = Get(isHidden, isDisabled, false, false);
  82. return Ok(users);
  83. }
  84. /// <summary>
  85. /// Gets a list of publicly visible users for display on a login screen.
  86. /// </summary>
  87. /// <response code="200">Public users returned.</response>
  88. /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the public users.</returns>
  89. [HttpGet("Public")]
  90. [ProducesResponseType(StatusCodes.Status200OK)]
  91. public ActionResult<IEnumerable<UserDto>> GetPublicUsers()
  92. {
  93. // If the startup wizard hasn't been completed then just return all users
  94. if (!_config.Configuration.IsStartupWizardCompleted)
  95. {
  96. return Ok(Get(false, false, false, false));
  97. }
  98. return Ok(Get(false, false, true, true));
  99. }
  100. /// <summary>
  101. /// Gets a user by Id.
  102. /// </summary>
  103. /// <param name="userId">The user id.</param>
  104. /// <response code="200">User returned.</response>
  105. /// <response code="404">User not found.</response>
  106. /// <returns>An <see cref="UserDto"/> with information about the user or a <see cref="NotFoundResult"/> if the user was not found.</returns>
  107. [HttpGet("{userId}")]
  108. [Authorize(Policy = Policies.IgnoreParentalControl)]
  109. [ProducesResponseType(StatusCodes.Status200OK)]
  110. [ProducesResponseType(StatusCodes.Status404NotFound)]
  111. public ActionResult<UserDto> GetUserById([FromRoute, Required] Guid userId)
  112. {
  113. var user = _userManager.GetUserById(userId);
  114. if (user == null)
  115. {
  116. return NotFound("User not found");
  117. }
  118. var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString());
  119. return result;
  120. }
  121. /// <summary>
  122. /// Deletes a user.
  123. /// </summary>
  124. /// <param name="userId">The user id.</param>
  125. /// <response code="204">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("{userId}")]
  129. [Authorize(Policy = Policies.RequiresElevation)]
  130. [ProducesResponseType(StatusCodes.Status204NoContent)]
  131. [ProducesResponseType(StatusCodes.Status404NotFound)]
  132. public async Task<ActionResult> DeleteUser([FromRoute, Required] Guid userId)
  133. {
  134. var user = _userManager.GetUserById(userId);
  135. _sessionManager.RevokeUserTokens(user.Id, null);
  136. await _userManager.DeleteUserAsync(userId).ConfigureAwait(false);
  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, Required] string pw,
  156. [FromQuery] 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 StatusCode(StatusCodes.Status403Forbidden, "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, Required] 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.GetNormalizedRemoteIp().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.GetNormalizedRemoteIp()}] {e.Message}", e);
  206. }
  207. }
  208. /// <summary>
  209. /// Authenticates a user with quick connect.
  210. /// </summary>
  211. /// <param name="request">The <see cref="QuickConnectDto"/> request.</param>
  212. /// <response code="200">User authenticated.</response>
  213. /// <response code="400">Missing token.</response>
  214. /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
  215. [HttpPost("AuthenticateWithQuickConnect")]
  216. [ProducesResponseType(StatusCodes.Status200OK)]
  217. public async Task<ActionResult<AuthenticationResult>> AuthenticateWithQuickConnect([FromBody, Required] QuickConnectDto request)
  218. {
  219. var auth = _authContext.GetAuthorizationInfo(Request);
  220. try
  221. {
  222. var authRequest = new AuthenticationRequest
  223. {
  224. App = auth.Client,
  225. AppVersion = auth.Version,
  226. DeviceId = auth.DeviceId,
  227. DeviceName = auth.Device,
  228. };
  229. return await _sessionManager.AuthenticateQuickConnect(
  230. authRequest,
  231. request.Token).ConfigureAwait(false);
  232. }
  233. catch (SecurityException e)
  234. {
  235. // rethrow adding IP address to message
  236. throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
  237. }
  238. }
  239. /// <summary>
  240. /// Updates a user's password.
  241. /// </summary>
  242. /// <param name="userId">The user id.</param>
  243. /// <param name="request">The <see cref="UpdateUserPassword"/> request.</param>
  244. /// <response code="204">Password successfully reset.</response>
  245. /// <response code="403">User is not allowed to update the password.</response>
  246. /// <response code="404">User not found.</response>
  247. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  248. [HttpPost("{userId}/Password")]
  249. [Authorize(Policy = Policies.DefaultAuthorization)]
  250. [ProducesResponseType(StatusCodes.Status204NoContent)]
  251. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  252. [ProducesResponseType(StatusCodes.Status404NotFound)]
  253. public async Task<ActionResult> UpdateUserPassword(
  254. [FromRoute, Required] Guid userId,
  255. [FromBody, Required] UpdateUserPassword request)
  256. {
  257. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true))
  258. {
  259. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password.");
  260. }
  261. var user = _userManager.GetUserById(userId);
  262. if (user == null)
  263. {
  264. return NotFound("User not found");
  265. }
  266. if (request.ResetPassword)
  267. {
  268. await _userManager.ResetPassword(user).ConfigureAwait(false);
  269. }
  270. else
  271. {
  272. var success = await _userManager.AuthenticateUser(
  273. user.Username,
  274. request.CurrentPw,
  275. request.CurrentPw,
  276. HttpContext.GetNormalizedRemoteIp().ToString(),
  277. false).ConfigureAwait(false);
  278. if (success == null)
  279. {
  280. return StatusCode(StatusCodes.Status403Forbidden, "Invalid user or password entered.");
  281. }
  282. await _userManager.ChangePassword(user, request.NewPw).ConfigureAwait(false);
  283. var currentToken = _authContext.GetAuthorizationInfo(Request).Token;
  284. _sessionManager.RevokeUserTokens(user.Id, currentToken);
  285. }
  286. return NoContent();
  287. }
  288. /// <summary>
  289. /// Updates a user's easy password.
  290. /// </summary>
  291. /// <param name="userId">The user id.</param>
  292. /// <param name="request">The <see cref="UpdateUserEasyPassword"/> request.</param>
  293. /// <response code="204">Password successfully reset.</response>
  294. /// <response code="403">User is not allowed to update the password.</response>
  295. /// <response code="404">User not found.</response>
  296. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
  297. [HttpPost("{userId}/EasyPassword")]
  298. [Authorize(Policy = Policies.DefaultAuthorization)]
  299. [ProducesResponseType(StatusCodes.Status204NoContent)]
  300. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  301. [ProducesResponseType(StatusCodes.Status404NotFound)]
  302. public ActionResult UpdateUserEasyPassword(
  303. [FromRoute, Required] Guid userId,
  304. [FromBody, Required] UpdateUserEasyPassword request)
  305. {
  306. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true))
  307. {
  308. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the easy password.");
  309. }
  310. var user = _userManager.GetUserById(userId);
  311. if (user == null)
  312. {
  313. return NotFound("User not found");
  314. }
  315. if (request.ResetPassword)
  316. {
  317. _userManager.ResetEasyPassword(user);
  318. }
  319. else
  320. {
  321. _userManager.ChangeEasyPassword(user, request.NewPw, request.NewPassword);
  322. }
  323. return NoContent();
  324. }
  325. /// <summary>
  326. /// Updates a user.
  327. /// </summary>
  328. /// <param name="userId">The user id.</param>
  329. /// <param name="updateUser">The updated user model.</param>
  330. /// <response code="204">User updated.</response>
  331. /// <response code="400">User information was not supplied.</response>
  332. /// <response code="403">User update forbidden.</response>
  333. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
  334. [HttpPost("{userId}")]
  335. [Authorize(Policy = Policies.DefaultAuthorization)]
  336. [ProducesResponseType(StatusCodes.Status204NoContent)]
  337. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  338. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  339. public async Task<ActionResult> UpdateUser(
  340. [FromRoute, Required] Guid userId,
  341. [FromBody, Required] UserDto updateUser)
  342. {
  343. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false))
  344. {
  345. return StatusCode(StatusCodes.Status403Forbidden, "User update not allowed.");
  346. }
  347. var user = _userManager.GetUserById(userId);
  348. if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
  349. {
  350. await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
  351. }
  352. await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false);
  353. return NoContent();
  354. }
  355. /// <summary>
  356. /// Updates a user policy.
  357. /// </summary>
  358. /// <param name="userId">The user id.</param>
  359. /// <param name="newPolicy">The new user policy.</param>
  360. /// <response code="204">User policy updated.</response>
  361. /// <response code="400">User policy was not supplied.</response>
  362. /// <response code="403">User policy update forbidden.</response>
  363. /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure..</returns>
  364. [HttpPost("{userId}/Policy")]
  365. [Authorize(Policy = Policies.RequiresElevation)]
  366. [ProducesResponseType(StatusCodes.Status204NoContent)]
  367. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  368. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  369. public async Task<ActionResult> UpdateUserPolicy(
  370. [FromRoute, Required] Guid userId,
  371. [FromBody, Required] UserPolicy newPolicy)
  372. {
  373. var user = _userManager.GetUserById(userId);
  374. // If removing admin access
  375. if (!newPolicy.IsAdministrator && user.HasPermission(PermissionKind.IsAdministrator))
  376. {
  377. if (_userManager.Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  378. {
  379. return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one user in the system with administrative access.");
  380. }
  381. }
  382. // If disabling
  383. if (newPolicy.IsDisabled && user.HasPermission(PermissionKind.IsAdministrator))
  384. {
  385. return StatusCode(StatusCodes.Status403Forbidden, "Administrators cannot be disabled.");
  386. }
  387. // If disabling
  388. if (newPolicy.IsDisabled && !user.HasPermission(PermissionKind.IsDisabled))
  389. {
  390. if (_userManager.Users.Count(i => !i.HasPermission(PermissionKind.IsDisabled)) == 1)
  391. {
  392. return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one enabled user in the system.");
  393. }
  394. var currentToken = _authContext.GetAuthorizationInfo(Request).Token;
  395. _sessionManager.RevokeUserTokens(user.Id, currentToken);
  396. }
  397. await _userManager.UpdatePolicyAsync(userId, newPolicy).ConfigureAwait(false);
  398. return NoContent();
  399. }
  400. /// <summary>
  401. /// Updates a user configuration.
  402. /// </summary>
  403. /// <param name="userId">The user id.</param>
  404. /// <param name="userConfig">The new user configuration.</param>
  405. /// <response code="204">User configuration updated.</response>
  406. /// <response code="403">User configuration update forbidden.</response>
  407. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  408. [HttpPost("{userId}/Configuration")]
  409. [Authorize(Policy = Policies.DefaultAuthorization)]
  410. [ProducesResponseType(StatusCodes.Status204NoContent)]
  411. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  412. public async Task<ActionResult> UpdateUserConfiguration(
  413. [FromRoute, Required] Guid userId,
  414. [FromBody, Required] UserConfiguration userConfig)
  415. {
  416. if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false))
  417. {
  418. return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed");
  419. }
  420. await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false);
  421. return NoContent();
  422. }
  423. /// <summary>
  424. /// Creates a user.
  425. /// </summary>
  426. /// <param name="request">The create user by name request body.</param>
  427. /// <response code="200">User created.</response>
  428. /// <returns>An <see cref="UserDto"/> of the new user.</returns>
  429. [HttpPost("New")]
  430. [Authorize(Policy = Policies.RequiresElevation)]
  431. [ProducesResponseType(StatusCodes.Status200OK)]
  432. public async Task<ActionResult<UserDto>> CreateUserByName([FromBody, Required] CreateUserByName request)
  433. {
  434. var newUser = await _userManager.CreateUserAsync(request.Name).ConfigureAwait(false);
  435. // no need to authenticate password for new user
  436. if (request.Password != null)
  437. {
  438. await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false);
  439. }
  440. var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString());
  441. return result;
  442. }
  443. /// <summary>
  444. /// Initiates the forgot password process for a local user.
  445. /// </summary>
  446. /// <param name="forgotPasswordRequest">The forgot password request containing the entered username.</param>
  447. /// <response code="200">Password reset process started.</response>
  448. /// <returns>A <see cref="Task"/> containing a <see cref="ForgotPasswordResult"/>.</returns>
  449. [HttpPost("ForgotPassword")]
  450. [ProducesResponseType(StatusCodes.Status200OK)]
  451. public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
  452. {
  453. var ip = HttpContext.GetNormalizedRemoteIp();
  454. var isLocal = HttpContext.IsLocal()
  455. || _networkManager.IsInLocalNetwork(ip);
  456. if (isLocal)
  457. {
  458. _logger.LogWarning("Password reset proccess initiated from outside the local network with IP: {IP}", ip);
  459. }
  460. var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);
  461. return result;
  462. }
  463. /// <summary>
  464. /// Redeems a forgot password pin.
  465. /// </summary>
  466. /// <param name="forgotPasswordPinRequest">The forgot password pin request containing the entered pin.</param>
  467. /// <response code="200">Pin reset process started.</response>
  468. /// <returns>A <see cref="Task"/> containing a <see cref="PinRedeemResult"/>.</returns>
  469. [HttpPost("ForgotPassword/Pin")]
  470. [ProducesResponseType(StatusCodes.Status200OK)]
  471. public async Task<ActionResult<PinRedeemResult>> ForgotPasswordPin([FromBody, Required] ForgotPasswordPinDto forgotPasswordPinRequest)
  472. {
  473. var result = await _userManager.RedeemPasswordResetPin(forgotPasswordPinRequest.Pin).ConfigureAwait(false);
  474. return result;
  475. }
  476. /// <summary>
  477. /// Gets the user based on auth token.
  478. /// </summary>
  479. /// <response code="200">User returned.</response>
  480. /// <response code="400">Token is not owned by a user.</response>
  481. /// <returns>A <see cref="UserDto"/> for the authenticated user.</returns>
  482. [HttpGet("Me")]
  483. [Authorize(Policy = Policies.DefaultAuthorization)]
  484. [ProducesResponseType(StatusCodes.Status200OK)]
  485. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  486. public ActionResult<UserDto> GetCurrentUser()
  487. {
  488. var userId = ClaimHelpers.GetUserId(Request.HttpContext.User);
  489. if (userId == null)
  490. {
  491. return BadRequest();
  492. }
  493. var user = _userManager.GetUserById(userId.Value);
  494. if (user == null)
  495. {
  496. return BadRequest();
  497. }
  498. return _userManager.GetUserDto(user);
  499. }
  500. private IEnumerable<UserDto> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
  501. {
  502. var users = _userManager.Users;
  503. if (isDisabled.HasValue)
  504. {
  505. users = users.Where(i => i.HasPermission(PermissionKind.IsDisabled) == isDisabled.Value);
  506. }
  507. if (isHidden.HasValue)
  508. {
  509. users = users.Where(i => i.HasPermission(PermissionKind.IsHidden) == isHidden.Value);
  510. }
  511. if (filterByDevice)
  512. {
  513. var deviceId = _authContext.GetAuthorizationInfo(Request).DeviceId;
  514. if (!string.IsNullOrWhiteSpace(deviceId))
  515. {
  516. users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
  517. }
  518. }
  519. if (filterByNetwork)
  520. {
  521. if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()))
  522. {
  523. users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
  524. }
  525. }
  526. var result = users
  527. .OrderBy(u => u.Username)
  528. .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString()));
  529. return result;
  530. }
  531. }
  532. }