UserManager.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Events;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Authentication;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Devices;
  16. using MediaBrowser.Controller.Drawing;
  17. using MediaBrowser.Controller.Dto;
  18. using MediaBrowser.Controller.Entities;
  19. using MediaBrowser.Controller.Library;
  20. using MediaBrowser.Controller.Net;
  21. using MediaBrowser.Controller.Persistence;
  22. using MediaBrowser.Controller.Plugins;
  23. using MediaBrowser.Controller.Providers;
  24. using MediaBrowser.Controller.Security;
  25. using MediaBrowser.Controller.Session;
  26. using MediaBrowser.Model.Configuration;
  27. using MediaBrowser.Model.Cryptography;
  28. using MediaBrowser.Model.Dto;
  29. using MediaBrowser.Model.Entities;
  30. using MediaBrowser.Model.Events;
  31. using MediaBrowser.Model.IO;
  32. using MediaBrowser.Model.Serialization;
  33. using MediaBrowser.Model.Users;
  34. using Microsoft.Extensions.Logging;
  35. namespace Emby.Server.Implementations.Library
  36. {
  37. /// <summary>
  38. /// Class UserManager
  39. /// </summary>
  40. public class UserManager : IUserManager
  41. {
  42. /// <summary>
  43. /// Gets the users.
  44. /// </summary>
  45. /// <value>The users.</value>
  46. public IEnumerable<User> Users => _users;
  47. private User[] _users;
  48. /// <summary>
  49. /// The _logger
  50. /// </summary>
  51. private readonly ILogger _logger;
  52. /// <summary>
  53. /// Gets or sets the configuration manager.
  54. /// </summary>
  55. /// <value>The configuration manager.</value>
  56. private IServerConfigurationManager ConfigurationManager { get; set; }
  57. /// <summary>
  58. /// Gets the active user repository
  59. /// </summary>
  60. /// <value>The user repository.</value>
  61. private IUserRepository UserRepository { get; set; }
  62. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  63. private readonly IXmlSerializer _xmlSerializer;
  64. private readonly IJsonSerializer _jsonSerializer;
  65. private readonly INetworkManager _networkManager;
  66. private readonly Func<IImageProcessor> _imageProcessorFactory;
  67. private readonly Func<IDtoService> _dtoServiceFactory;
  68. private readonly IServerApplicationHost _appHost;
  69. private readonly IFileSystem _fileSystem;
  70. private IAuthenticationProvider[] _authenticationProviders;
  71. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  72. public UserManager(
  73. ILoggerFactory loggerFactory,
  74. IServerConfigurationManager configurationManager,
  75. IUserRepository userRepository,
  76. IXmlSerializer xmlSerializer,
  77. INetworkManager networkManager,
  78. Func<IImageProcessor> imageProcessorFactory,
  79. Func<IDtoService> dtoServiceFactory,
  80. IServerApplicationHost appHost,
  81. IJsonSerializer jsonSerializer,
  82. IFileSystem fileSystem)
  83. {
  84. _logger = loggerFactory.CreateLogger(nameof(UserManager));
  85. UserRepository = userRepository;
  86. _xmlSerializer = xmlSerializer;
  87. _networkManager = networkManager;
  88. _imageProcessorFactory = imageProcessorFactory;
  89. _dtoServiceFactory = dtoServiceFactory;
  90. _appHost = appHost;
  91. _jsonSerializer = jsonSerializer;
  92. _fileSystem = fileSystem;
  93. ConfigurationManager = configurationManager;
  94. _users = Array.Empty<User>();
  95. DeletePinFile();
  96. }
  97. public NameIdPair[] GetAuthenticationProviders()
  98. {
  99. return _authenticationProviders
  100. .Where(i => i.IsEnabled)
  101. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  102. .ThenBy(i => i.Name)
  103. .Select(i => new NameIdPair
  104. {
  105. Name = i.Name,
  106. Id = GetAuthenticationProviderId(i)
  107. })
  108. .ToArray();
  109. }
  110. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders)
  111. {
  112. _authenticationProviders = authenticationProviders.ToArray();
  113. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  114. }
  115. #region UserUpdated Event
  116. /// <summary>
  117. /// Occurs when [user updated].
  118. /// </summary>
  119. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  120. public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
  121. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  122. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  123. /// <summary>
  124. /// Called when [user updated].
  125. /// </summary>
  126. /// <param name="user">The user.</param>
  127. private void OnUserUpdated(User user)
  128. {
  129. UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  130. }
  131. #endregion
  132. #region UserDeleted Event
  133. /// <summary>
  134. /// Occurs when [user deleted].
  135. /// </summary>
  136. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  137. /// <summary>
  138. /// Called when [user deleted].
  139. /// </summary>
  140. /// <param name="user">The user.</param>
  141. private void OnUserDeleted(User user)
  142. {
  143. UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  144. }
  145. #endregion
  146. /// <summary>
  147. /// Gets a User by Id
  148. /// </summary>
  149. /// <param name="id">The id.</param>
  150. /// <returns>User.</returns>
  151. /// <exception cref="ArgumentNullException"></exception>
  152. public User GetUserById(Guid id)
  153. {
  154. if (id == Guid.Empty)
  155. {
  156. throw new ArgumentException(nameof(id), "Guid can't be empty");
  157. }
  158. return Users.FirstOrDefault(u => u.Id == id);
  159. }
  160. /// <summary>
  161. /// Gets the user by identifier.
  162. /// </summary>
  163. /// <param name="id">The identifier.</param>
  164. /// <returns>User.</returns>
  165. public User GetUserById(string id)
  166. {
  167. return GetUserById(new Guid(id));
  168. }
  169. public User GetUserByName(string name)
  170. {
  171. if (string.IsNullOrWhiteSpace(name))
  172. {
  173. throw new ArgumentNullException(nameof(name));
  174. }
  175. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  176. }
  177. public void Initialize()
  178. {
  179. _users = LoadUsers();
  180. var users = Users.ToList();
  181. // If there are no local users with admin rights, make them all admins
  182. if (!users.Any(i => i.Policy.IsAdministrator))
  183. {
  184. foreach (var user in users)
  185. {
  186. user.Policy.IsAdministrator = true;
  187. UpdateUserPolicy(user, user.Policy, false);
  188. }
  189. }
  190. }
  191. public static bool IsValidUsername(string username)
  192. {
  193. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  194. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  195. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
  196. return Regex.IsMatch(username, @"^[\w\-'._@]*$");
  197. }
  198. private static bool IsValidUsernameCharacter(char i)
  199. {
  200. return IsValidUsername(i.ToString());
  201. }
  202. public string MakeValidUsername(string username)
  203. {
  204. if (IsValidUsername(username))
  205. {
  206. return username;
  207. }
  208. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  209. var builder = new StringBuilder();
  210. foreach (var c in username)
  211. {
  212. if (IsValidUsernameCharacter(c))
  213. {
  214. builder.Append(c);
  215. }
  216. }
  217. return builder.ToString();
  218. }
  219. public async Task<User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
  220. {
  221. if (string.IsNullOrWhiteSpace(username))
  222. {
  223. throw new ArgumentNullException(nameof(username));
  224. }
  225. var user = Users
  226. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  227. var success = false;
  228. IAuthenticationProvider authenticationProvider = null;
  229. if (user != null)
  230. {
  231. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  232. authenticationProvider = authResult.Item1;
  233. success = authResult.Item2;
  234. }
  235. else
  236. {
  237. // user is null
  238. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  239. authenticationProvider = authResult.Item1;
  240. success = authResult.Item2;
  241. if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
  242. {
  243. user = await CreateUser(username).ConfigureAwait(false);
  244. var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy;
  245. if (hasNewUserPolicy != null)
  246. {
  247. var policy = hasNewUserPolicy.GetNewUserPolicy();
  248. UpdateUserPolicy(user, policy, true);
  249. }
  250. }
  251. }
  252. if (success && user != null && authenticationProvider != null)
  253. {
  254. var providerId = GetAuthenticationProviderId(authenticationProvider);
  255. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  256. {
  257. user.Policy.AuthenticationProviderId = providerId;
  258. UpdateUserPolicy(user, user.Policy, true);
  259. }
  260. }
  261. if (user == null)
  262. {
  263. throw new SecurityException("Invalid username or password entered.");
  264. }
  265. if (user.Policy.IsDisabled)
  266. {
  267. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  268. }
  269. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  270. {
  271. throw new SecurityException("Forbidden.");
  272. }
  273. if (!user.IsParentalScheduleAllowed())
  274. {
  275. throw new SecurityException("User is not allowed access at this time.");
  276. }
  277. // Update LastActivityDate and LastLoginDate, then save
  278. if (success)
  279. {
  280. if (isUserSession)
  281. {
  282. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  283. UpdateUser(user);
  284. }
  285. UpdateInvalidLoginAttemptCount(user, 0);
  286. }
  287. else
  288. {
  289. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  290. }
  291. _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  292. return success ? user : null;
  293. }
  294. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  295. {
  296. return provider.GetType().FullName;
  297. }
  298. private IAuthenticationProvider GetAuthenticationProvider(User user)
  299. {
  300. return GetAuthenticationProviders(user).First();
  301. }
  302. private IAuthenticationProvider[] GetAuthenticationProviders(User user)
  303. {
  304. var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
  305. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  306. if (!string.IsNullOrEmpty(authenticationProviderId))
  307. {
  308. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  309. }
  310. if (providers.Length == 0)
  311. {
  312. providers = new IAuthenticationProvider[] { _defaultAuthenticationProvider };
  313. }
  314. return providers;
  315. }
  316. private async Task<bool> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
  317. {
  318. try
  319. {
  320. var requiresResolvedUser = provider as IRequiresResolvedUser;
  321. if (requiresResolvedUser != null)
  322. {
  323. await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
  324. }
  325. else
  326. {
  327. await provider.Authenticate(username, password).ConfigureAwait(false);
  328. }
  329. return true;
  330. }
  331. catch (Exception ex)
  332. {
  333. _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name);
  334. return false;
  335. }
  336. }
  337. private async Task<Tuple<IAuthenticationProvider, bool>> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
  338. {
  339. bool success = false;
  340. IAuthenticationProvider authenticationProvider = null;
  341. if (password != null && user != null)
  342. {
  343. // Doesn't look like this is even possible to be used, because of password == null checks below
  344. hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
  345. }
  346. if (password == null)
  347. {
  348. // legacy
  349. success = string.Equals(_defaultAuthenticationProvider.GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  350. }
  351. else
  352. {
  353. foreach (var provider in GetAuthenticationProviders(user))
  354. {
  355. success = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  356. if (success)
  357. {
  358. authenticationProvider = provider;
  359. break;
  360. }
  361. }
  362. }
  363. if (user != null)
  364. {
  365. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  366. {
  367. if (password == null)
  368. {
  369. // legacy
  370. success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  371. }
  372. else
  373. {
  374. success = string.Equals(GetLocalPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  375. }
  376. }
  377. }
  378. return new Tuple<IAuthenticationProvider, bool>(authenticationProvider, success);
  379. }
  380. private void UpdateInvalidLoginAttemptCount(User user, int newValue)
  381. {
  382. if (user.Policy.InvalidLoginAttemptCount == newValue || newValue <= 0)
  383. {
  384. return;
  385. }
  386. user.Policy.InvalidLoginAttemptCount = newValue;
  387. // Check for users without a value here and then fill in the default value
  388. // also protect from an always lockout if misconfigured
  389. if (user.Policy.LoginAttemptsBeforeLockout == null || user.Policy.LoginAttemptsBeforeLockout == 0)
  390. {
  391. user.Policy.LoginAttemptsBeforeLockout = user.Policy.IsAdministrator ? 5 : 3;
  392. }
  393. var maxCount = user.Policy.LoginAttemptsBeforeLockout;
  394. var fireLockout = false;
  395. // -1 can be used to specify no lockout value
  396. if (maxCount != -1 && newValue >= maxCount)
  397. {
  398. _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue);
  399. user.Policy.IsDisabled = true;
  400. fireLockout = true;
  401. }
  402. UpdateUserPolicy(user, user.Policy, false);
  403. if (fireLockout)
  404. {
  405. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  406. }
  407. }
  408. private string GetLocalPasswordHash(User user)
  409. {
  410. return string.IsNullOrEmpty(user.EasyPassword)
  411. ? null
  412. : user.EasyPassword;
  413. }
  414. /// <summary>
  415. /// Loads the users from the repository
  416. /// </summary>
  417. /// <returns>IEnumerable{User}.</returns>
  418. private User[] LoadUsers()
  419. {
  420. var users = UserRepository.RetrieveAllUsers();
  421. // There always has to be at least one user.
  422. if (users.Count == 0)
  423. {
  424. var defaultName = Environment.UserName;
  425. if (string.IsNullOrWhiteSpace(defaultName))
  426. {
  427. defaultName = "MyJellyfinUser";
  428. }
  429. var name = MakeValidUsername(defaultName);
  430. var user = InstantiateNewUser(name);
  431. user.DateLastSaved = DateTime.UtcNow;
  432. UserRepository.CreateUser(user);
  433. users.Add(user);
  434. user.Policy.IsAdministrator = true;
  435. user.Policy.EnableContentDeletion = true;
  436. user.Policy.EnableRemoteControlOfOtherUsers = true;
  437. UpdateUserPolicy(user, user.Policy, false);
  438. }
  439. return users.ToArray();
  440. }
  441. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  442. {
  443. if (user == null)
  444. {
  445. throw new ArgumentNullException(nameof(user));
  446. }
  447. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
  448. bool hasConfiguredEasyPassword = string.IsNullOrEmpty(GetLocalPasswordHash(user));
  449. bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  450. hasConfiguredEasyPassword :
  451. hasConfiguredPassword;
  452. UserDto dto = new UserDto
  453. {
  454. Id = user.Id,
  455. Name = user.Name,
  456. HasPassword = hasPassword,
  457. HasConfiguredPassword = hasConfiguredPassword,
  458. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  459. LastActivityDate = user.LastActivityDate,
  460. LastLoginDate = user.LastLoginDate,
  461. Configuration = user.Configuration,
  462. ServerId = _appHost.SystemId,
  463. Policy = user.Policy
  464. };
  465. if (!hasPassword && Users.Count() == 1)
  466. {
  467. dto.EnableAutoLogin = true;
  468. }
  469. ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
  470. if (image != null)
  471. {
  472. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  473. try
  474. {
  475. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  476. }
  477. catch (Exception ex)
  478. {
  479. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  480. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
  481. }
  482. }
  483. return dto;
  484. }
  485. public UserDto GetOfflineUserDto(User user)
  486. {
  487. var dto = GetUserDto(user);
  488. dto.ServerName = _appHost.FriendlyName;
  489. return dto;
  490. }
  491. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  492. {
  493. try
  494. {
  495. return _imageProcessorFactory().GetImageCacheTag(item, image);
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
  500. return null;
  501. }
  502. }
  503. /// <summary>
  504. /// Refreshes metadata for each user
  505. /// </summary>
  506. /// <param name="cancellationToken">The cancellation token.</param>
  507. /// <returns>Task.</returns>
  508. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  509. {
  510. foreach (var user in Users)
  511. {
  512. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
  513. }
  514. }
  515. /// <summary>
  516. /// Renames the user.
  517. /// </summary>
  518. /// <param name="user">The user.</param>
  519. /// <param name="newName">The new name.</param>
  520. /// <returns>Task.</returns>
  521. /// <exception cref="ArgumentNullException">user</exception>
  522. /// <exception cref="ArgumentException"></exception>
  523. public async Task RenameUser(User user, string newName)
  524. {
  525. if (user == null)
  526. {
  527. throw new ArgumentNullException(nameof(user));
  528. }
  529. if (string.IsNullOrEmpty(newName))
  530. {
  531. throw new ArgumentNullException(nameof(newName));
  532. }
  533. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  534. {
  535. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  536. }
  537. if (user.Name.Equals(newName, StringComparison.Ordinal))
  538. {
  539. throw new ArgumentException("The new and old names must be different.");
  540. }
  541. await user.Rename(newName);
  542. OnUserUpdated(user);
  543. }
  544. /// <summary>
  545. /// Updates the user.
  546. /// </summary>
  547. /// <param name="user">The user.</param>
  548. /// <exception cref="ArgumentNullException">user</exception>
  549. /// <exception cref="ArgumentException"></exception>
  550. public void UpdateUser(User user)
  551. {
  552. if (user == null)
  553. {
  554. throw new ArgumentNullException(nameof(user));
  555. }
  556. if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
  557. {
  558. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  559. }
  560. user.DateModified = DateTime.UtcNow;
  561. user.DateLastSaved = DateTime.UtcNow;
  562. UserRepository.UpdateUser(user);
  563. OnUserUpdated(user);
  564. }
  565. public event EventHandler<GenericEventArgs<User>> UserCreated;
  566. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  567. /// <summary>
  568. /// Creates the user.
  569. /// </summary>
  570. /// <param name="name">The name.</param>
  571. /// <returns>User.</returns>
  572. /// <exception cref="ArgumentNullException">name</exception>
  573. /// <exception cref="ArgumentException"></exception>
  574. public async Task<User> CreateUser(string name)
  575. {
  576. if (string.IsNullOrWhiteSpace(name))
  577. {
  578. throw new ArgumentNullException(nameof(name));
  579. }
  580. if (!IsValidUsername(name))
  581. {
  582. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  583. }
  584. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  585. {
  586. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  587. }
  588. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  589. try
  590. {
  591. var user = InstantiateNewUser(name);
  592. var list = Users.ToList();
  593. list.Add(user);
  594. _users = list.ToArray();
  595. user.DateLastSaved = DateTime.UtcNow;
  596. UserRepository.CreateUser(user);
  597. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  598. return user;
  599. }
  600. finally
  601. {
  602. _userListLock.Release();
  603. }
  604. }
  605. /// <summary>
  606. /// Deletes the user.
  607. /// </summary>
  608. /// <param name="user">The user.</param>
  609. /// <returns>Task.</returns>
  610. /// <exception cref="ArgumentNullException">user</exception>
  611. /// <exception cref="ArgumentException"></exception>
  612. public async Task DeleteUser(User user)
  613. {
  614. if (user == null)
  615. {
  616. throw new ArgumentNullException(nameof(user));
  617. }
  618. var allUsers = Users.ToList();
  619. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  620. {
  621. throw new ArgumentException(string.Format("The user cannot be deleted because there is no user with the Name {0} and Id {1}.", user.Name, user.Id));
  622. }
  623. if (allUsers.Count == 1)
  624. {
  625. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  626. }
  627. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  628. {
  629. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one admin user in the system.", user.Name));
  630. }
  631. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  632. try
  633. {
  634. var configPath = GetConfigurationFilePath(user);
  635. UserRepository.DeleteUser(user);
  636. try
  637. {
  638. _fileSystem.DeleteFile(configPath);
  639. }
  640. catch (IOException ex)
  641. {
  642. _logger.LogError(ex, "Error deleting file {path}", configPath);
  643. }
  644. DeleteUserPolicy(user);
  645. _users = allUsers.Where(i => i.Id != user.Id).ToArray();
  646. OnUserDeleted(user);
  647. }
  648. finally
  649. {
  650. _userListLock.Release();
  651. }
  652. }
  653. /// <summary>
  654. /// Resets the password by clearing it.
  655. /// </summary>
  656. /// <returns>Task.</returns>
  657. public Task ResetPassword(User user)
  658. {
  659. return ChangePassword(user, string.Empty);
  660. }
  661. public void ResetEasyPassword(User user)
  662. {
  663. ChangeEasyPassword(user, string.Empty, null);
  664. }
  665. public async Task ChangePassword(User user, string newPassword)
  666. {
  667. if (user == null)
  668. {
  669. throw new ArgumentNullException(nameof(user));
  670. }
  671. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  672. UpdateUser(user);
  673. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  674. }
  675. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  676. {
  677. if (user == null)
  678. {
  679. throw new ArgumentNullException(nameof(user));
  680. }
  681. if (newPassword != null)
  682. {
  683. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  684. }
  685. if (string.IsNullOrWhiteSpace(newPasswordHash))
  686. {
  687. throw new ArgumentNullException(nameof(newPasswordHash));
  688. }
  689. user.EasyPassword = newPasswordHash;
  690. UpdateUser(user);
  691. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  692. }
  693. /// <summary>
  694. /// Instantiates the new user.
  695. /// </summary>
  696. /// <param name="name">The name.</param>
  697. /// <returns>User.</returns>
  698. private static User InstantiateNewUser(string name)
  699. {
  700. return new User
  701. {
  702. Name = name,
  703. Id = Guid.NewGuid(),
  704. DateCreated = DateTime.UtcNow,
  705. DateModified = DateTime.UtcNow,
  706. UsesIdForConfigurationPath = true,
  707. //Salt = BCrypt.GenerateSalt()
  708. };
  709. }
  710. private string PasswordResetFile => Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt");
  711. private string _lastPin;
  712. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  713. private int _pinAttempts;
  714. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  715. {
  716. var num = new Random().Next(1, 9999);
  717. var path = PasswordResetFile;
  718. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  719. _lastPin = pin;
  720. var time = TimeSpan.FromMinutes(5);
  721. var expiration = DateTime.UtcNow.Add(time);
  722. var text = new StringBuilder();
  723. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  724. text.AppendLine("Use your web browser to visit:");
  725. text.AppendLine(string.Empty);
  726. text.AppendLine(localAddress + "/web/index.html#!/forgotpasswordpin.html");
  727. text.AppendLine(string.Empty);
  728. text.AppendLine("Enter the following pin code:");
  729. text.AppendLine(string.Empty);
  730. text.AppendLine(pin);
  731. text.AppendLine(string.Empty);
  732. var localExpirationTime = expiration.ToLocalTime();
  733. // Tuesday, 22 August 2006 06:30 AM
  734. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  735. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  736. var result = new PasswordPinCreationResult
  737. {
  738. PinFile = path,
  739. ExpirationDate = expiration
  740. };
  741. _lastPasswordPinCreationResult = result;
  742. _pinAttempts = 0;
  743. return result;
  744. }
  745. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  746. {
  747. DeletePinFile();
  748. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  749. null :
  750. GetUserByName(enteredUsername);
  751. var action = ForgotPasswordAction.InNetworkRequired;
  752. string pinFile = null;
  753. DateTime? expirationDate = null;
  754. if (user != null && !user.Policy.IsAdministrator)
  755. {
  756. action = ForgotPasswordAction.ContactAdmin;
  757. }
  758. else
  759. {
  760. if (isInNetwork)
  761. {
  762. action = ForgotPasswordAction.PinCode;
  763. }
  764. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  765. pinFile = result.PinFile;
  766. expirationDate = result.ExpirationDate;
  767. }
  768. return new ForgotPasswordResult
  769. {
  770. Action = action,
  771. PinFile = pinFile,
  772. PinExpirationDate = expirationDate
  773. };
  774. }
  775. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  776. {
  777. DeletePinFile();
  778. var usersReset = new List<string>();
  779. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  780. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  781. _lastPasswordPinCreationResult != null &&
  782. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  783. if (valid)
  784. {
  785. _lastPin = null;
  786. _lastPasswordPinCreationResult = null;
  787. foreach (var user in Users)
  788. {
  789. await ResetPassword(user).ConfigureAwait(false);
  790. if (user.Policy.IsDisabled)
  791. {
  792. user.Policy.IsDisabled = false;
  793. UpdateUserPolicy(user, user.Policy, true);
  794. }
  795. usersReset.Add(user.Name);
  796. }
  797. }
  798. else
  799. {
  800. _pinAttempts++;
  801. if (_pinAttempts >= 3)
  802. {
  803. _lastPin = null;
  804. _lastPasswordPinCreationResult = null;
  805. }
  806. }
  807. return new PinRedeemResult
  808. {
  809. Success = valid,
  810. UsersReset = usersReset.ToArray()
  811. };
  812. }
  813. private void DeletePinFile()
  814. {
  815. try
  816. {
  817. _fileSystem.DeleteFile(PasswordResetFile);
  818. }
  819. catch
  820. {
  821. }
  822. }
  823. class PasswordPinCreationResult
  824. {
  825. public string PinFile { get; set; }
  826. public DateTime ExpirationDate { get; set; }
  827. }
  828. public UserPolicy GetUserPolicy(User user)
  829. {
  830. var path = GetPolicyFilePath(user);
  831. if (!File.Exists(path))
  832. {
  833. return GetDefaultPolicy(user);
  834. }
  835. try
  836. {
  837. lock (_policySyncLock)
  838. {
  839. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  840. }
  841. }
  842. catch (IOException)
  843. {
  844. return GetDefaultPolicy(user);
  845. }
  846. catch (Exception ex)
  847. {
  848. _logger.LogError(ex, "Error reading policy file: {path}", path);
  849. return GetDefaultPolicy(user);
  850. }
  851. }
  852. private static UserPolicy GetDefaultPolicy(User user)
  853. {
  854. return new UserPolicy
  855. {
  856. EnableContentDownloading = true,
  857. EnableSyncTranscoding = true
  858. };
  859. }
  860. private readonly object _policySyncLock = new object();
  861. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  862. {
  863. var user = GetUserById(userId);
  864. UpdateUserPolicy(user, userPolicy, true);
  865. }
  866. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  867. {
  868. // The xml serializer will output differently if the type is not exact
  869. if (userPolicy.GetType() != typeof(UserPolicy))
  870. {
  871. var json = _jsonSerializer.SerializeToString(userPolicy);
  872. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  873. }
  874. var path = GetPolicyFilePath(user);
  875. Directory.CreateDirectory(Path.GetDirectoryName(path));
  876. lock (_policySyncLock)
  877. {
  878. _xmlSerializer.SerializeToFile(userPolicy, path);
  879. user.Policy = userPolicy;
  880. }
  881. if (fireEvent)
  882. {
  883. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  884. }
  885. }
  886. private void DeleteUserPolicy(User user)
  887. {
  888. var path = GetPolicyFilePath(user);
  889. try
  890. {
  891. lock (_policySyncLock)
  892. {
  893. _fileSystem.DeleteFile(path);
  894. }
  895. }
  896. catch (IOException)
  897. {
  898. }
  899. catch (Exception ex)
  900. {
  901. _logger.LogError(ex, "Error deleting policy file");
  902. }
  903. }
  904. private static string GetPolicyFilePath(User user)
  905. {
  906. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  907. }
  908. private static string GetConfigurationFilePath(User user)
  909. {
  910. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  911. }
  912. public UserConfiguration GetUserConfiguration(User user)
  913. {
  914. var path = GetConfigurationFilePath(user);
  915. if (!File.Exists(path))
  916. {
  917. return new UserConfiguration();
  918. }
  919. try
  920. {
  921. lock (_configSyncLock)
  922. {
  923. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  924. }
  925. }
  926. catch (IOException)
  927. {
  928. return new UserConfiguration();
  929. }
  930. catch (Exception ex)
  931. {
  932. _logger.LogError(ex, "Error reading policy file: {path}", path);
  933. return new UserConfiguration();
  934. }
  935. }
  936. private readonly object _configSyncLock = new object();
  937. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  938. {
  939. var user = GetUserById(userId);
  940. UpdateConfiguration(user, config);
  941. }
  942. public void UpdateConfiguration(User user, UserConfiguration config)
  943. {
  944. UpdateConfiguration(user, config, true);
  945. }
  946. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  947. {
  948. var path = GetConfigurationFilePath(user);
  949. // The xml serializer will output differently if the type is not exact
  950. if (config.GetType() != typeof(UserConfiguration))
  951. {
  952. var json = _jsonSerializer.SerializeToString(config);
  953. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  954. }
  955. Directory.CreateDirectory(Path.GetDirectoryName(path));
  956. lock (_configSyncLock)
  957. {
  958. _xmlSerializer.SerializeToFile(config, path);
  959. user.Configuration = config;
  960. }
  961. if (fireEvent)
  962. {
  963. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  964. }
  965. }
  966. }
  967. public class DeviceAccessEntryPoint : IServerEntryPoint
  968. {
  969. private IUserManager _userManager;
  970. private IAuthenticationRepository _authRepo;
  971. private IDeviceManager _deviceManager;
  972. private ISessionManager _sessionManager;
  973. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  974. {
  975. _userManager = userManager;
  976. _authRepo = authRepo;
  977. _deviceManager = deviceManager;
  978. _sessionManager = sessionManager;
  979. }
  980. public Task RunAsync()
  981. {
  982. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  983. return Task.CompletedTask;
  984. }
  985. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  986. {
  987. var user = e.Argument;
  988. if (!user.Policy.EnableAllDevices)
  989. {
  990. UpdateDeviceAccess(user);
  991. }
  992. }
  993. private void UpdateDeviceAccess(User user)
  994. {
  995. var existing = _authRepo.Get(new AuthenticationInfoQuery
  996. {
  997. UserId = user.Id
  998. }).Items;
  999. foreach (var authInfo in existing)
  1000. {
  1001. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  1002. {
  1003. _sessionManager.Logout(authInfo);
  1004. }
  1005. }
  1006. }
  1007. public void Dispose()
  1008. {
  1009. }
  1010. }
  1011. }