UserManager.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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), 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. var maxCount = user.Policy.IsAdministrator ? 3 : 5;
  388. var fireLockout = false;
  389. if (newValue >= maxCount)
  390. {
  391. _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue);
  392. user.Policy.IsDisabled = true;
  393. fireLockout = true;
  394. }
  395. UpdateUserPolicy(user, user.Policy, false);
  396. if (fireLockout)
  397. {
  398. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  399. }
  400. }
  401. private string GetLocalPasswordHash(User user)
  402. {
  403. return string.IsNullOrEmpty(user.EasyPassword)
  404. ? null
  405. : user.EasyPassword;
  406. }
  407. private bool IsPasswordEmpty(User user, string passwordHash)
  408. {
  409. return string.IsNullOrEmpty(passwordHash);
  410. }
  411. /// <summary>
  412. /// Loads the users from the repository
  413. /// </summary>
  414. /// <returns>IEnumerable{User}.</returns>
  415. private User[] LoadUsers()
  416. {
  417. var users = UserRepository.RetrieveAllUsers();
  418. // There always has to be at least one user.
  419. if (users.Count == 0)
  420. {
  421. var defaultName = Environment.UserName;
  422. if (string.IsNullOrWhiteSpace(defaultName))
  423. {
  424. defaultName = "MyJellyfinUser";
  425. }
  426. var name = MakeValidUsername(defaultName);
  427. var user = InstantiateNewUser(name);
  428. user.DateLastSaved = DateTime.UtcNow;
  429. UserRepository.CreateUser(user);
  430. users.Add(user);
  431. user.Policy.IsAdministrator = true;
  432. user.Policy.EnableContentDeletion = true;
  433. user.Policy.EnableRemoteControlOfOtherUsers = true;
  434. UpdateUserPolicy(user, user.Policy, false);
  435. }
  436. return users.ToArray();
  437. }
  438. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  439. {
  440. if (user == null)
  441. {
  442. throw new ArgumentNullException(nameof(user));
  443. }
  444. var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
  445. var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
  446. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  447. hasConfiguredEasyPassword :
  448. hasConfiguredPassword;
  449. var dto = new UserDto
  450. {
  451. Id = user.Id,
  452. Name = user.Name,
  453. HasPassword = hasPassword,
  454. HasConfiguredPassword = hasConfiguredPassword,
  455. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  456. LastActivityDate = user.LastActivityDate,
  457. LastLoginDate = user.LastLoginDate,
  458. Configuration = user.Configuration,
  459. ServerId = _appHost.SystemId,
  460. Policy = user.Policy
  461. };
  462. if (!hasPassword && Users.Count() == 1)
  463. {
  464. dto.EnableAutoLogin = true;
  465. }
  466. var image = user.GetImageInfo(ImageType.Primary, 0);
  467. if (image != null)
  468. {
  469. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  470. try
  471. {
  472. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  473. }
  474. catch (Exception ex)
  475. {
  476. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  477. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
  478. }
  479. }
  480. return dto;
  481. }
  482. public UserDto GetOfflineUserDto(User user)
  483. {
  484. var dto = GetUserDto(user);
  485. dto.ServerName = _appHost.FriendlyName;
  486. return dto;
  487. }
  488. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  489. {
  490. try
  491. {
  492. return _imageProcessorFactory().GetImageCacheTag(item, image);
  493. }
  494. catch (Exception ex)
  495. {
  496. _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
  497. return null;
  498. }
  499. }
  500. /// <summary>
  501. /// Refreshes metadata for each user
  502. /// </summary>
  503. /// <param name="cancellationToken">The cancellation token.</param>
  504. /// <returns>Task.</returns>
  505. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  506. {
  507. foreach (var user in Users)
  508. {
  509. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
  510. }
  511. }
  512. /// <summary>
  513. /// Renames the user.
  514. /// </summary>
  515. /// <param name="user">The user.</param>
  516. /// <param name="newName">The new name.</param>
  517. /// <returns>Task.</returns>
  518. /// <exception cref="ArgumentNullException">user</exception>
  519. /// <exception cref="ArgumentException"></exception>
  520. public async Task RenameUser(User user, string newName)
  521. {
  522. if (user == null)
  523. {
  524. throw new ArgumentNullException(nameof(user));
  525. }
  526. if (string.IsNullOrEmpty(newName))
  527. {
  528. throw new ArgumentNullException(nameof(newName));
  529. }
  530. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  531. {
  532. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  533. }
  534. if (user.Name.Equals(newName, StringComparison.Ordinal))
  535. {
  536. throw new ArgumentException("The new and old names must be different.");
  537. }
  538. await user.Rename(newName);
  539. OnUserUpdated(user);
  540. }
  541. /// <summary>
  542. /// Updates the user.
  543. /// </summary>
  544. /// <param name="user">The user.</param>
  545. /// <exception cref="ArgumentNullException">user</exception>
  546. /// <exception cref="ArgumentException"></exception>
  547. public void UpdateUser(User user)
  548. {
  549. if (user == null)
  550. {
  551. throw new ArgumentNullException(nameof(user));
  552. }
  553. if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
  554. {
  555. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  556. }
  557. user.DateModified = DateTime.UtcNow;
  558. user.DateLastSaved = DateTime.UtcNow;
  559. UserRepository.UpdateUser(user);
  560. OnUserUpdated(user);
  561. }
  562. public event EventHandler<GenericEventArgs<User>> UserCreated;
  563. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  564. /// <summary>
  565. /// Creates the user.
  566. /// </summary>
  567. /// <param name="name">The name.</param>
  568. /// <returns>User.</returns>
  569. /// <exception cref="ArgumentNullException">name</exception>
  570. /// <exception cref="ArgumentException"></exception>
  571. public async Task<User> CreateUser(string name)
  572. {
  573. if (string.IsNullOrWhiteSpace(name))
  574. {
  575. throw new ArgumentNullException(nameof(name));
  576. }
  577. if (!IsValidUsername(name))
  578. {
  579. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  580. }
  581. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  582. {
  583. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  584. }
  585. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  586. try
  587. {
  588. var user = InstantiateNewUser(name);
  589. var list = Users.ToList();
  590. list.Add(user);
  591. _users = list.ToArray();
  592. user.DateLastSaved = DateTime.UtcNow;
  593. UserRepository.CreateUser(user);
  594. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  595. return user;
  596. }
  597. finally
  598. {
  599. _userListLock.Release();
  600. }
  601. }
  602. /// <summary>
  603. /// Deletes the user.
  604. /// </summary>
  605. /// <param name="user">The user.</param>
  606. /// <returns>Task.</returns>
  607. /// <exception cref="ArgumentNullException">user</exception>
  608. /// <exception cref="ArgumentException"></exception>
  609. public async Task DeleteUser(User user)
  610. {
  611. if (user == null)
  612. {
  613. throw new ArgumentNullException(nameof(user));
  614. }
  615. var allUsers = Users.ToList();
  616. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  617. {
  618. 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));
  619. }
  620. if (allUsers.Count == 1)
  621. {
  622. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  623. }
  624. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  625. {
  626. 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));
  627. }
  628. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  629. try
  630. {
  631. var configPath = GetConfigurationFilePath(user);
  632. UserRepository.DeleteUser(user);
  633. try
  634. {
  635. _fileSystem.DeleteFile(configPath);
  636. }
  637. catch (IOException ex)
  638. {
  639. _logger.LogError(ex, "Error deleting file {path}", configPath);
  640. }
  641. DeleteUserPolicy(user);
  642. _users = allUsers.Where(i => i.Id != user.Id).ToArray();
  643. OnUserDeleted(user);
  644. }
  645. finally
  646. {
  647. _userListLock.Release();
  648. }
  649. }
  650. /// <summary>
  651. /// Resets the password by clearing it.
  652. /// </summary>
  653. /// <returns>Task.</returns>
  654. public Task ResetPassword(User user)
  655. {
  656. return ChangePassword(user, string.Empty);
  657. }
  658. public void ResetEasyPassword(User user)
  659. {
  660. ChangeEasyPassword(user, string.Empty, null);
  661. }
  662. public async Task ChangePassword(User user, string newPassword)
  663. {
  664. if (user == null)
  665. {
  666. throw new ArgumentNullException(nameof(user));
  667. }
  668. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  669. UpdateUser(user);
  670. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  671. }
  672. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  673. {
  674. if (user == null)
  675. {
  676. throw new ArgumentNullException(nameof(user));
  677. }
  678. if (newPassword != null)
  679. {
  680. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  681. }
  682. if (string.IsNullOrWhiteSpace(newPasswordHash))
  683. {
  684. throw new ArgumentNullException(nameof(newPasswordHash));
  685. }
  686. user.EasyPassword = newPasswordHash;
  687. UpdateUser(user);
  688. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  689. }
  690. /// <summary>
  691. /// Instantiates the new user.
  692. /// </summary>
  693. /// <param name="name">The name.</param>
  694. /// <returns>User.</returns>
  695. private static User InstantiateNewUser(string name)
  696. {
  697. return new User
  698. {
  699. Name = name,
  700. Id = Guid.NewGuid(),
  701. DateCreated = DateTime.UtcNow,
  702. DateModified = DateTime.UtcNow,
  703. UsesIdForConfigurationPath = true,
  704. //Salt = BCrypt.GenerateSalt()
  705. };
  706. }
  707. private string PasswordResetFile => Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt");
  708. private string _lastPin;
  709. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  710. private int _pinAttempts;
  711. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  712. {
  713. var num = new Random().Next(1, 9999);
  714. var path = PasswordResetFile;
  715. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  716. _lastPin = pin;
  717. var time = TimeSpan.FromMinutes(5);
  718. var expiration = DateTime.UtcNow.Add(time);
  719. var text = new StringBuilder();
  720. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  721. text.AppendLine("Use your web browser to visit:");
  722. text.AppendLine(string.Empty);
  723. text.AppendLine(localAddress + "/web/index.html#!/forgotpasswordpin.html");
  724. text.AppendLine(string.Empty);
  725. text.AppendLine("Enter the following pin code:");
  726. text.AppendLine(string.Empty);
  727. text.AppendLine(pin);
  728. text.AppendLine(string.Empty);
  729. var localExpirationTime = expiration.ToLocalTime();
  730. // Tuesday, 22 August 2006 06:30 AM
  731. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  732. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  733. var result = new PasswordPinCreationResult
  734. {
  735. PinFile = path,
  736. ExpirationDate = expiration
  737. };
  738. _lastPasswordPinCreationResult = result;
  739. _pinAttempts = 0;
  740. return result;
  741. }
  742. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  743. {
  744. DeletePinFile();
  745. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  746. null :
  747. GetUserByName(enteredUsername);
  748. var action = ForgotPasswordAction.InNetworkRequired;
  749. string pinFile = null;
  750. DateTime? expirationDate = null;
  751. if (user != null && !user.Policy.IsAdministrator)
  752. {
  753. action = ForgotPasswordAction.ContactAdmin;
  754. }
  755. else
  756. {
  757. if (isInNetwork)
  758. {
  759. action = ForgotPasswordAction.PinCode;
  760. }
  761. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  762. pinFile = result.PinFile;
  763. expirationDate = result.ExpirationDate;
  764. }
  765. return new ForgotPasswordResult
  766. {
  767. Action = action,
  768. PinFile = pinFile,
  769. PinExpirationDate = expirationDate
  770. };
  771. }
  772. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  773. {
  774. DeletePinFile();
  775. var usersReset = new List<string>();
  776. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  777. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  778. _lastPasswordPinCreationResult != null &&
  779. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  780. if (valid)
  781. {
  782. _lastPin = null;
  783. _lastPasswordPinCreationResult = null;
  784. foreach (var user in Users)
  785. {
  786. await ResetPassword(user).ConfigureAwait(false);
  787. if (user.Policy.IsDisabled)
  788. {
  789. user.Policy.IsDisabled = false;
  790. UpdateUserPolicy(user, user.Policy, true);
  791. }
  792. usersReset.Add(user.Name);
  793. }
  794. }
  795. else
  796. {
  797. _pinAttempts++;
  798. if (_pinAttempts >= 3)
  799. {
  800. _lastPin = null;
  801. _lastPasswordPinCreationResult = null;
  802. }
  803. }
  804. return new PinRedeemResult
  805. {
  806. Success = valid,
  807. UsersReset = usersReset.ToArray()
  808. };
  809. }
  810. private void DeletePinFile()
  811. {
  812. try
  813. {
  814. _fileSystem.DeleteFile(PasswordResetFile);
  815. }
  816. catch
  817. {
  818. }
  819. }
  820. class PasswordPinCreationResult
  821. {
  822. public string PinFile { get; set; }
  823. public DateTime ExpirationDate { get; set; }
  824. }
  825. public UserPolicy GetUserPolicy(User user)
  826. {
  827. var path = GetPolicyFilePath(user);
  828. if (!File.Exists(path))
  829. {
  830. return GetDefaultPolicy(user);
  831. }
  832. try
  833. {
  834. lock (_policySyncLock)
  835. {
  836. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  837. }
  838. }
  839. catch (IOException)
  840. {
  841. return GetDefaultPolicy(user);
  842. }
  843. catch (Exception ex)
  844. {
  845. _logger.LogError(ex, "Error reading policy file: {path}", path);
  846. return GetDefaultPolicy(user);
  847. }
  848. }
  849. private static UserPolicy GetDefaultPolicy(User user)
  850. {
  851. return new UserPolicy
  852. {
  853. EnableContentDownloading = true,
  854. EnableSyncTranscoding = true
  855. };
  856. }
  857. private readonly object _policySyncLock = new object();
  858. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  859. {
  860. var user = GetUserById(userId);
  861. UpdateUserPolicy(user, userPolicy, true);
  862. }
  863. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  864. {
  865. // The xml serializer will output differently if the type is not exact
  866. if (userPolicy.GetType() != typeof(UserPolicy))
  867. {
  868. var json = _jsonSerializer.SerializeToString(userPolicy);
  869. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  870. }
  871. var path = GetPolicyFilePath(user);
  872. Directory.CreateDirectory(Path.GetDirectoryName(path));
  873. lock (_policySyncLock)
  874. {
  875. _xmlSerializer.SerializeToFile(userPolicy, path);
  876. user.Policy = userPolicy;
  877. }
  878. if (fireEvent)
  879. {
  880. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  881. }
  882. }
  883. private void DeleteUserPolicy(User user)
  884. {
  885. var path = GetPolicyFilePath(user);
  886. try
  887. {
  888. lock (_policySyncLock)
  889. {
  890. _fileSystem.DeleteFile(path);
  891. }
  892. }
  893. catch (IOException)
  894. {
  895. }
  896. catch (Exception ex)
  897. {
  898. _logger.LogError(ex, "Error deleting policy file");
  899. }
  900. }
  901. private static string GetPolicyFilePath(User user)
  902. {
  903. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  904. }
  905. private static string GetConfigurationFilePath(User user)
  906. {
  907. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  908. }
  909. public UserConfiguration GetUserConfiguration(User user)
  910. {
  911. var path = GetConfigurationFilePath(user);
  912. if (!File.Exists(path))
  913. {
  914. return new UserConfiguration();
  915. }
  916. try
  917. {
  918. lock (_configSyncLock)
  919. {
  920. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  921. }
  922. }
  923. catch (IOException)
  924. {
  925. return new UserConfiguration();
  926. }
  927. catch (Exception ex)
  928. {
  929. _logger.LogError(ex, "Error reading policy file: {path}", path);
  930. return new UserConfiguration();
  931. }
  932. }
  933. private readonly object _configSyncLock = new object();
  934. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  935. {
  936. var user = GetUserById(userId);
  937. UpdateConfiguration(user, config);
  938. }
  939. public void UpdateConfiguration(User user, UserConfiguration config)
  940. {
  941. UpdateConfiguration(user, config, true);
  942. }
  943. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  944. {
  945. var path = GetConfigurationFilePath(user);
  946. // The xml serializer will output differently if the type is not exact
  947. if (config.GetType() != typeof(UserConfiguration))
  948. {
  949. var json = _jsonSerializer.SerializeToString(config);
  950. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  951. }
  952. Directory.CreateDirectory(Path.GetDirectoryName(path));
  953. lock (_configSyncLock)
  954. {
  955. _xmlSerializer.SerializeToFile(config, path);
  956. user.Configuration = config;
  957. }
  958. if (fireEvent)
  959. {
  960. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  961. }
  962. }
  963. }
  964. public class DeviceAccessEntryPoint : IServerEntryPoint
  965. {
  966. private IUserManager _userManager;
  967. private IAuthenticationRepository _authRepo;
  968. private IDeviceManager _deviceManager;
  969. private ISessionManager _sessionManager;
  970. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  971. {
  972. _userManager = userManager;
  973. _authRepo = authRepo;
  974. _deviceManager = deviceManager;
  975. _sessionManager = sessionManager;
  976. }
  977. public Task RunAsync()
  978. {
  979. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  980. return Task.CompletedTask;
  981. }
  982. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  983. {
  984. var user = e.Argument;
  985. if (!user.Policy.EnableAllDevices)
  986. {
  987. UpdateDeviceAccess(user);
  988. }
  989. }
  990. private void UpdateDeviceAccess(User user)
  991. {
  992. var existing = _authRepo.Get(new AuthenticationInfoQuery
  993. {
  994. UserId = user.Id
  995. }).Items;
  996. foreach (var authInfo in existing)
  997. {
  998. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  999. {
  1000. _sessionManager.Logout(authInfo);
  1001. }
  1002. }
  1003. }
  1004. public void Dispose()
  1005. {
  1006. }
  1007. }
  1008. }