UserManager.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Channels;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Connect;
  9. using MediaBrowser.Controller.Drawing;
  10. using MediaBrowser.Controller.Dto;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Net;
  14. using MediaBrowser.Controller.Persistence;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Channels;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Connect;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.Events;
  22. using MediaBrowser.Model.Logging;
  23. using MediaBrowser.Model.Querying;
  24. using MediaBrowser.Model.Serialization;
  25. using MediaBrowser.Model.Users;
  26. using System;
  27. using System.Collections.Generic;
  28. using System.Globalization;
  29. using System.IO;
  30. using System.Linq;
  31. using System.Security.Cryptography;
  32. using System.Text;
  33. using System.Threading;
  34. using System.Threading.Tasks;
  35. namespace MediaBrowser.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 { get; private set; }
  47. /// <summary>
  48. /// The _logger
  49. /// </summary>
  50. private readonly ILogger _logger;
  51. /// <summary>
  52. /// Gets or sets the configuration manager.
  53. /// </summary>
  54. /// <value>The configuration manager.</value>
  55. private IServerConfigurationManager ConfigurationManager { get; set; }
  56. /// <summary>
  57. /// Gets the active user repository
  58. /// </summary>
  59. /// <value>The user repository.</value>
  60. private IUserRepository UserRepository { get; set; }
  61. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  62. private readonly IXmlSerializer _xmlSerializer;
  63. private readonly IJsonSerializer _jsonSerializer;
  64. private readonly INetworkManager _networkManager;
  65. private readonly Func<IImageProcessor> _imageProcessorFactory;
  66. private readonly Func<IDtoService> _dtoServiceFactory;
  67. private readonly Func<IConnectManager> _connectFactory;
  68. private readonly Func<IChannelManager> _channelManager;
  69. private readonly Func<ILibraryManager> _libraryManager;
  70. private readonly IServerApplicationHost _appHost;
  71. private readonly IFileSystem _fileSystem;
  72. public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory, Func<IConnectManager> connectFactory, IServerApplicationHost appHost, IJsonSerializer jsonSerializer, IFileSystem fileSystem, Func<IChannelManager> channelManager, Func<ILibraryManager> libraryManager)
  73. {
  74. _logger = logger;
  75. UserRepository = userRepository;
  76. _xmlSerializer = xmlSerializer;
  77. _networkManager = networkManager;
  78. _imageProcessorFactory = imageProcessorFactory;
  79. _dtoServiceFactory = dtoServiceFactory;
  80. _connectFactory = connectFactory;
  81. _appHost = appHost;
  82. _jsonSerializer = jsonSerializer;
  83. _fileSystem = fileSystem;
  84. _channelManager = channelManager;
  85. _libraryManager = libraryManager;
  86. ConfigurationManager = configurationManager;
  87. Users = new List<User>();
  88. DeletePinFile();
  89. }
  90. #region UserUpdated Event
  91. /// <summary>
  92. /// Occurs when [user updated].
  93. /// </summary>
  94. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  95. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  96. /// <summary>
  97. /// Called when [user updated].
  98. /// </summary>
  99. /// <param name="user">The user.</param>
  100. private void OnUserUpdated(User user)
  101. {
  102. EventHelper.FireEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  103. }
  104. #endregion
  105. #region UserDeleted Event
  106. /// <summary>
  107. /// Occurs when [user deleted].
  108. /// </summary>
  109. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  110. /// <summary>
  111. /// Called when [user deleted].
  112. /// </summary>
  113. /// <param name="user">The user.</param>
  114. private void OnUserDeleted(User user)
  115. {
  116. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  117. }
  118. #endregion
  119. /// <summary>
  120. /// Gets a User by Id
  121. /// </summary>
  122. /// <param name="id">The id.</param>
  123. /// <returns>User.</returns>
  124. /// <exception cref="System.ArgumentNullException"></exception>
  125. public User GetUserById(Guid id)
  126. {
  127. if (id == Guid.Empty)
  128. {
  129. throw new ArgumentNullException("id");
  130. }
  131. return Users.FirstOrDefault(u => u.Id == id);
  132. }
  133. /// <summary>
  134. /// Gets the user by identifier.
  135. /// </summary>
  136. /// <param name="id">The identifier.</param>
  137. /// <returns>User.</returns>
  138. public User GetUserById(string id)
  139. {
  140. return GetUserById(new Guid(id));
  141. }
  142. public User GetUserByName(string name)
  143. {
  144. if (string.IsNullOrWhiteSpace(name))
  145. {
  146. throw new ArgumentNullException("name");
  147. }
  148. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  149. }
  150. public async Task Initialize()
  151. {
  152. Users = await LoadUsers().ConfigureAwait(false);
  153. var users = Users.ToList();
  154. foreach (var user in users)
  155. {
  156. await DoPolicyMigration(user).ConfigureAwait(false);
  157. await DoChannelMigration(user).ConfigureAwait(false);
  158. await DoLibraryMigration(user).ConfigureAwait(false);
  159. }
  160. // If there are no local users with admin rights, make them all admins
  161. if (!users.Any(i => i.Policy.IsAdministrator))
  162. {
  163. foreach (var user in users)
  164. {
  165. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value == UserLinkType.LinkedUser)
  166. {
  167. user.Policy.IsAdministrator = true;
  168. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  169. }
  170. }
  171. }
  172. }
  173. public Task<bool> AuthenticateUser(string username, string passwordSha1, string remoteEndPoint)
  174. {
  175. return AuthenticateUser(username, passwordSha1, null, remoteEndPoint);
  176. }
  177. public bool IsValidUsername(string username)
  178. {
  179. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  180. return username.All(IsValidCharacter);
  181. }
  182. private bool IsValidCharacter(char i)
  183. {
  184. return char.IsLetterOrDigit(i) || char.Equals(i, '-') || char.Equals(i, '_') || char.Equals(i, '\'') ||
  185. char.Equals(i, '.');
  186. }
  187. public string MakeValidUsername(string username)
  188. {
  189. if (IsValidUsername(username))
  190. {
  191. return username;
  192. }
  193. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  194. var builder = new StringBuilder();
  195. foreach (var c in username)
  196. {
  197. if (IsValidCharacter(c))
  198. {
  199. builder.Append(c);
  200. }
  201. }
  202. return builder.ToString();
  203. }
  204. public async Task<bool> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint)
  205. {
  206. if (string.IsNullOrWhiteSpace(username))
  207. {
  208. throw new ArgumentNullException("username");
  209. }
  210. var user = Users
  211. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  212. if (user == null)
  213. {
  214. throw new SecurityException("Invalid username or password entered.");
  215. }
  216. if (user.Policy.IsDisabled)
  217. {
  218. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  219. }
  220. var success = false;
  221. // Authenticate using local credentials if not a guest
  222. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  223. {
  224. success = string.Equals(GetPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  225. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  226. {
  227. success = string.Equals(GetLocalPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  228. }
  229. }
  230. // Update LastActivityDate and LastLoginDate, then save
  231. if (success)
  232. {
  233. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  234. await UpdateUser(user).ConfigureAwait(false);
  235. }
  236. _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  237. return success;
  238. }
  239. private string GetPasswordHash(User user)
  240. {
  241. return string.IsNullOrEmpty(user.Password)
  242. ? GetSha1String(string.Empty)
  243. : user.Password;
  244. }
  245. private string GetLocalPasswordHash(User user)
  246. {
  247. return string.IsNullOrEmpty(user.LocalPassword)
  248. ? GetSha1String(string.Empty)
  249. : user.LocalPassword;
  250. }
  251. private bool IsPasswordEmpty(string passwordHash)
  252. {
  253. return string.Equals(passwordHash, GetSha1String(string.Empty), StringComparison.OrdinalIgnoreCase);
  254. }
  255. /// <summary>
  256. /// Gets the sha1 string.
  257. /// </summary>
  258. /// <param name="str">The STR.</param>
  259. /// <returns>System.String.</returns>
  260. private static string GetSha1String(string str)
  261. {
  262. using (var provider = SHA1.Create())
  263. {
  264. var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
  265. return BitConverter.ToString(hash).Replace("-", string.Empty);
  266. }
  267. }
  268. /// <summary>
  269. /// Loads the users from the repository
  270. /// </summary>
  271. /// <returns>IEnumerable{User}.</returns>
  272. private async Task<IEnumerable<User>> LoadUsers()
  273. {
  274. var users = UserRepository.RetrieveAllUsers().ToList();
  275. // There always has to be at least one user.
  276. if (users.Count == 0)
  277. {
  278. var name = MakeValidUsername(Environment.UserName);
  279. var user = InstantiateNewUser(name, false);
  280. user.DateLastSaved = DateTime.UtcNow;
  281. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  282. users.Add(user);
  283. user.Policy.IsAdministrator = true;
  284. user.Policy.EnableRemoteControlOfOtherUsers = true;
  285. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  286. }
  287. return users;
  288. }
  289. private async Task DoPolicyMigration(User user)
  290. {
  291. if (!user.Configuration.HasMigratedToPolicy)
  292. {
  293. user.Policy.BlockUnratedItems = user.Configuration.BlockUnratedItems;
  294. user.Policy.EnableContentDeletion = user.Configuration.EnableContentDeletion;
  295. user.Policy.EnableLiveTvAccess = user.Configuration.EnableLiveTvAccess;
  296. user.Policy.EnableLiveTvManagement = user.Configuration.EnableLiveTvManagement;
  297. user.Policy.EnableMediaPlayback = user.Configuration.EnableMediaPlayback;
  298. user.Policy.IsAdministrator = user.Configuration.IsAdministrator;
  299. await UpdateUserPolicy(user, user.Policy, false);
  300. user.Configuration.HasMigratedToPolicy = true;
  301. await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false);
  302. }
  303. }
  304. private async Task DoChannelMigration(User user)
  305. {
  306. if (user.Policy.BlockedChannels != null)
  307. {
  308. if (user.Policy.BlockedChannels.Length > 0)
  309. {
  310. user.Policy.EnableAllChannels = false;
  311. try
  312. {
  313. var channelResult = await _channelManager().GetChannelsInternal(new ChannelQuery
  314. {
  315. UserId = user.Id.ToString("N")
  316. }, CancellationToken.None).ConfigureAwait(false);
  317. user.Policy.EnabledChannels = channelResult.Items
  318. .Select(i => i.Id.ToString("N"))
  319. .Except(user.Policy.BlockedChannels)
  320. .ToArray();
  321. }
  322. catch
  323. {
  324. user.Policy.EnabledChannels = new string[] { };
  325. }
  326. }
  327. else
  328. {
  329. user.Policy.EnableAllChannels = true;
  330. user.Policy.EnabledChannels = new string[] { };
  331. }
  332. user.Policy.BlockedChannels = null;
  333. await UpdateUserPolicy(user, user.Policy, false);
  334. }
  335. }
  336. private async Task DoLibraryMigration(User user)
  337. {
  338. if (user.Policy.BlockedMediaFolders != null)
  339. {
  340. if (user.Policy.BlockedMediaFolders.Length > 0)
  341. {
  342. user.Policy.EnableAllFolders = false;
  343. try
  344. {
  345. user.Policy.EnabledFolders = _libraryManager().RootFolder
  346. .Children
  347. .Where(i => !user.Policy.BlockedMediaFolders.Contains(i.Name, StringComparer.OrdinalIgnoreCase) && !user.Policy.BlockedMediaFolders.Contains(i.Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  348. .Select(i => i.Id.ToString("N"))
  349. .ToArray();
  350. }
  351. catch
  352. {
  353. user.Policy.EnabledFolders = new string[] { };
  354. }
  355. }
  356. else
  357. {
  358. user.Policy.EnableAllFolders = true;
  359. user.Policy.EnabledFolders = new string[] { };
  360. }
  361. user.Policy.BlockedMediaFolders = null;
  362. await UpdateUserPolicy(user, user.Policy, false);
  363. }
  364. }
  365. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  366. {
  367. if (user == null)
  368. {
  369. throw new ArgumentNullException("user");
  370. }
  371. var passwordHash = GetPasswordHash(user);
  372. var hasConfiguredDefaultPassword = !IsPasswordEmpty(passwordHash);
  373. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  374. !IsPasswordEmpty(GetLocalPasswordHash(user)) :
  375. hasConfiguredDefaultPassword;
  376. var dto = new UserDto
  377. {
  378. Id = user.Id.ToString("N"),
  379. Name = user.Name,
  380. HasPassword = hasPassword,
  381. HasConfiguredPassword = hasConfiguredDefaultPassword,
  382. LastActivityDate = user.LastActivityDate,
  383. LastLoginDate = user.LastLoginDate,
  384. Configuration = user.Configuration,
  385. ConnectLinkType = user.ConnectLinkType,
  386. ConnectUserId = user.ConnectUserId,
  387. ConnectUserName = user.ConnectUserName,
  388. ServerId = _appHost.SystemId,
  389. Policy = user.Policy
  390. };
  391. var image = user.GetImageInfo(ImageType.Primary, 0);
  392. if (image != null)
  393. {
  394. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  395. try
  396. {
  397. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user, new List<ItemFields>
  398. {
  399. ItemFields.PrimaryImageAspectRatio
  400. });
  401. }
  402. catch (Exception ex)
  403. {
  404. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  405. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  406. }
  407. }
  408. return dto;
  409. }
  410. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  411. {
  412. try
  413. {
  414. return _imageProcessorFactory().GetImageCacheTag(item, image);
  415. }
  416. catch (Exception ex)
  417. {
  418. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  419. return null;
  420. }
  421. }
  422. /// <summary>
  423. /// Refreshes metadata for each user
  424. /// </summary>
  425. /// <param name="cancellationToken">The cancellation token.</param>
  426. /// <returns>Task.</returns>
  427. public Task RefreshUsersMetadata(CancellationToken cancellationToken)
  428. {
  429. var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(), cancellationToken)).ToList();
  430. return Task.WhenAll(tasks);
  431. }
  432. /// <summary>
  433. /// Renames the user.
  434. /// </summary>
  435. /// <param name="user">The user.</param>
  436. /// <param name="newName">The new name.</param>
  437. /// <returns>Task.</returns>
  438. /// <exception cref="System.ArgumentNullException">user</exception>
  439. /// <exception cref="System.ArgumentException"></exception>
  440. public async Task RenameUser(User user, string newName)
  441. {
  442. if (user == null)
  443. {
  444. throw new ArgumentNullException("user");
  445. }
  446. if (string.IsNullOrEmpty(newName))
  447. {
  448. throw new ArgumentNullException("newName");
  449. }
  450. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  451. {
  452. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  453. }
  454. if (user.Name.Equals(newName, StringComparison.Ordinal))
  455. {
  456. throw new ArgumentException("The new and old names must be different.");
  457. }
  458. await user.Rename(newName);
  459. OnUserUpdated(user);
  460. }
  461. /// <summary>
  462. /// Updates the user.
  463. /// </summary>
  464. /// <param name="user">The user.</param>
  465. /// <exception cref="System.ArgumentNullException">user</exception>
  466. /// <exception cref="System.ArgumentException"></exception>
  467. public async Task UpdateUser(User user)
  468. {
  469. if (user == null)
  470. {
  471. throw new ArgumentNullException("user");
  472. }
  473. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  474. {
  475. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  476. }
  477. user.DateModified = DateTime.UtcNow;
  478. user.DateLastSaved = DateTime.UtcNow;
  479. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  480. OnUserUpdated(user);
  481. }
  482. public event EventHandler<GenericEventArgs<User>> UserCreated;
  483. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  484. /// <summary>
  485. /// Creates the user.
  486. /// </summary>
  487. /// <param name="name">The name.</param>
  488. /// <returns>User.</returns>
  489. /// <exception cref="System.ArgumentNullException">name</exception>
  490. /// <exception cref="System.ArgumentException"></exception>
  491. public async Task<User> CreateUser(string name)
  492. {
  493. if (string.IsNullOrWhiteSpace(name))
  494. {
  495. throw new ArgumentNullException("name");
  496. }
  497. if (!IsValidUsername(name))
  498. {
  499. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  500. }
  501. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  502. {
  503. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  504. }
  505. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  506. try
  507. {
  508. var user = InstantiateNewUser(name, true);
  509. var list = Users.ToList();
  510. list.Add(user);
  511. Users = list;
  512. user.DateLastSaved = DateTime.UtcNow;
  513. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  514. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  515. return user;
  516. }
  517. finally
  518. {
  519. _userListLock.Release();
  520. }
  521. }
  522. /// <summary>
  523. /// Deletes the user.
  524. /// </summary>
  525. /// <param name="user">The user.</param>
  526. /// <returns>Task.</returns>
  527. /// <exception cref="System.ArgumentNullException">user</exception>
  528. /// <exception cref="System.ArgumentException"></exception>
  529. public async Task DeleteUser(User user)
  530. {
  531. if (user == null)
  532. {
  533. throw new ArgumentNullException("user");
  534. }
  535. if (user.ConnectLinkType.HasValue)
  536. {
  537. await _connectFactory().RemoveConnect(user.Id.ToString("N")).ConfigureAwait(false);
  538. }
  539. var allUsers = Users.ToList();
  540. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  541. {
  542. 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));
  543. }
  544. if (allUsers.Count == 1)
  545. {
  546. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  547. }
  548. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  549. {
  550. 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));
  551. }
  552. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  553. try
  554. {
  555. var configPath = GetConfigurationFilePath(user);
  556. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  557. try
  558. {
  559. _fileSystem.DeleteFile(configPath);
  560. }
  561. catch (IOException ex)
  562. {
  563. _logger.ErrorException("Error deleting file {0}", ex, configPath);
  564. }
  565. DeleteUserPolicy(user);
  566. // Force this to be lazy loaded again
  567. Users = await LoadUsers().ConfigureAwait(false);
  568. OnUserDeleted(user);
  569. }
  570. finally
  571. {
  572. _userListLock.Release();
  573. }
  574. }
  575. /// <summary>
  576. /// Resets the password by clearing it.
  577. /// </summary>
  578. /// <returns>Task.</returns>
  579. public Task ResetPassword(User user)
  580. {
  581. return ChangePassword(user, GetSha1String(string.Empty));
  582. }
  583. /// <summary>
  584. /// Changes the password.
  585. /// </summary>
  586. /// <param name="user">The user.</param>
  587. /// <param name="newPasswordSha1">The new password sha1.</param>
  588. /// <returns>Task.</returns>
  589. /// <exception cref="System.ArgumentNullException">
  590. /// user
  591. /// or
  592. /// newPassword
  593. /// </exception>
  594. /// <exception cref="System.ArgumentException">Passwords for guests cannot be changed.</exception>
  595. public async Task ChangePassword(User user, string newPasswordSha1)
  596. {
  597. if (user == null)
  598. {
  599. throw new ArgumentNullException("user");
  600. }
  601. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  602. {
  603. throw new ArgumentNullException("newPasswordSha1");
  604. }
  605. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  606. {
  607. throw new ArgumentException("Passwords for guests cannot be changed.");
  608. }
  609. user.Password = newPasswordSha1;
  610. await UpdateUser(user).ConfigureAwait(false);
  611. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  612. }
  613. /// <summary>
  614. /// Instantiates the new user.
  615. /// </summary>
  616. /// <param name="name">The name.</param>
  617. /// <param name="checkId">if set to <c>true</c> [check identifier].</param>
  618. /// <returns>User.</returns>
  619. private User InstantiateNewUser(string name, bool checkId)
  620. {
  621. var id = ("MBUser" + name).GetMD5();
  622. if (checkId && Users.Select(i => i.Id).Contains(id))
  623. {
  624. id = Guid.NewGuid();
  625. }
  626. return new User
  627. {
  628. Name = name,
  629. Id = id,
  630. DateCreated = DateTime.UtcNow,
  631. DateModified = DateTime.UtcNow,
  632. UsesIdForConfigurationPath = true
  633. };
  634. }
  635. private string PasswordResetFile
  636. {
  637. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  638. }
  639. private string _lastPin;
  640. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  641. private int _pinAttempts;
  642. private PasswordPinCreationResult CreatePasswordResetPin()
  643. {
  644. var num = new Random().Next(1, 9999);
  645. var path = PasswordResetFile;
  646. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  647. _lastPin = pin;
  648. var time = TimeSpan.FromMinutes(5);
  649. var expiration = DateTime.UtcNow.Add(time);
  650. var text = new StringBuilder();
  651. var info = _appHost.GetSystemInfo();
  652. var localAddress = info.LocalAddress ?? string.Empty;
  653. text.AppendLine("Use your web browser to visit:");
  654. text.AppendLine(string.Empty);
  655. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  656. text.AppendLine(string.Empty);
  657. text.AppendLine("Enter the following pin code:");
  658. text.AppendLine(string.Empty);
  659. text.AppendLine(pin);
  660. text.AppendLine(string.Empty);
  661. text.AppendLine("The pin code will expire at " + expiration.ToLocalTime().ToShortDateString() + " " + expiration.ToLocalTime().ToShortTimeString());
  662. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  663. var result = new PasswordPinCreationResult
  664. {
  665. PinFile = path,
  666. ExpirationDate = expiration
  667. };
  668. _lastPasswordPinCreationResult = result;
  669. _pinAttempts = 0;
  670. return result;
  671. }
  672. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  673. {
  674. DeletePinFile();
  675. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  676. null :
  677. GetUserByName(enteredUsername);
  678. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  679. {
  680. throw new ArgumentException("Unable to process forgot password request for guests.");
  681. }
  682. var action = ForgotPasswordAction.InNetworkRequired;
  683. string pinFile = null;
  684. DateTime? expirationDate = null;
  685. if (user != null && !user.Policy.IsAdministrator)
  686. {
  687. action = ForgotPasswordAction.ContactAdmin;
  688. }
  689. else
  690. {
  691. if (isInNetwork)
  692. {
  693. action = ForgotPasswordAction.PinCode;
  694. }
  695. var result = CreatePasswordResetPin();
  696. pinFile = result.PinFile;
  697. expirationDate = result.ExpirationDate;
  698. }
  699. return new ForgotPasswordResult
  700. {
  701. Action = action,
  702. PinFile = pinFile,
  703. PinExpirationDate = expirationDate
  704. };
  705. }
  706. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  707. {
  708. DeletePinFile();
  709. var usersReset = new List<string>();
  710. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  711. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  712. _lastPasswordPinCreationResult != null &&
  713. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  714. if (valid)
  715. {
  716. _lastPin = null;
  717. _lastPasswordPinCreationResult = null;
  718. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  719. .ToList();
  720. foreach (var user in users)
  721. {
  722. await ResetPassword(user).ConfigureAwait(false);
  723. usersReset.Add(user.Name);
  724. }
  725. }
  726. else
  727. {
  728. _pinAttempts++;
  729. if (_pinAttempts >= 3)
  730. {
  731. _lastPin = null;
  732. _lastPasswordPinCreationResult = null;
  733. }
  734. }
  735. return new PinRedeemResult
  736. {
  737. Success = valid,
  738. UsersReset = usersReset.ToArray()
  739. };
  740. }
  741. private void DeletePinFile()
  742. {
  743. try
  744. {
  745. _fileSystem.DeleteFile(PasswordResetFile);
  746. }
  747. catch
  748. {
  749. }
  750. }
  751. class PasswordPinCreationResult
  752. {
  753. public string PinFile { get; set; }
  754. public DateTime ExpirationDate { get; set; }
  755. }
  756. public UserPolicy GetUserPolicy(User user)
  757. {
  758. var path = GetPolifyFilePath(user);
  759. try
  760. {
  761. lock (_policySyncLock)
  762. {
  763. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  764. }
  765. }
  766. catch (DirectoryNotFoundException)
  767. {
  768. return GetDefaultPolicy(user);
  769. }
  770. catch (FileNotFoundException)
  771. {
  772. return GetDefaultPolicy(user);
  773. }
  774. catch (Exception ex)
  775. {
  776. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  777. return GetDefaultPolicy(user);
  778. }
  779. }
  780. private UserPolicy GetDefaultPolicy(User user)
  781. {
  782. return new UserPolicy
  783. {
  784. EnableSync = true
  785. };
  786. }
  787. private readonly object _policySyncLock = new object();
  788. public Task UpdateUserPolicy(string userId, UserPolicy userPolicy)
  789. {
  790. var user = GetUserById(userId);
  791. return UpdateUserPolicy(user, userPolicy, true);
  792. }
  793. private async Task UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  794. {
  795. // The xml serializer will output differently if the type is not exact
  796. if (userPolicy.GetType() != typeof(UserPolicy))
  797. {
  798. var json = _jsonSerializer.SerializeToString(userPolicy);
  799. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  800. }
  801. var path = GetPolifyFilePath(user);
  802. Directory.CreateDirectory(Path.GetDirectoryName(path));
  803. lock (_policySyncLock)
  804. {
  805. _xmlSerializer.SerializeToFile(userPolicy, path);
  806. user.Policy = userPolicy;
  807. }
  808. user.Configuration.IsAdministrator = user.Policy.IsAdministrator;
  809. user.Configuration.EnableLiveTvManagement = user.Policy.EnableLiveTvManagement;
  810. user.Configuration.EnableLiveTvAccess = user.Policy.EnableLiveTvAccess;
  811. user.Configuration.EnableMediaPlayback = user.Policy.EnableMediaPlayback;
  812. user.Configuration.EnableContentDeletion = user.Policy.EnableContentDeletion;
  813. await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false);
  814. }
  815. private void DeleteUserPolicy(User user)
  816. {
  817. var path = GetPolifyFilePath(user);
  818. try
  819. {
  820. lock (_policySyncLock)
  821. {
  822. _fileSystem.DeleteFile(path);
  823. }
  824. }
  825. catch (IOException)
  826. {
  827. }
  828. catch (Exception ex)
  829. {
  830. _logger.ErrorException("Error deleting policy file", ex);
  831. }
  832. }
  833. private string GetPolifyFilePath(User user)
  834. {
  835. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  836. }
  837. private string GetConfigurationFilePath(User user)
  838. {
  839. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  840. }
  841. public UserConfiguration GetUserConfiguration(User user)
  842. {
  843. var path = GetConfigurationFilePath(user);
  844. try
  845. {
  846. lock (_configSyncLock)
  847. {
  848. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  849. }
  850. }
  851. catch (DirectoryNotFoundException)
  852. {
  853. return new UserConfiguration();
  854. }
  855. catch (FileNotFoundException)
  856. {
  857. return new UserConfiguration();
  858. }
  859. catch (Exception ex)
  860. {
  861. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  862. return new UserConfiguration();
  863. }
  864. }
  865. private readonly object _configSyncLock = new object();
  866. public Task UpdateConfiguration(string userId, UserConfiguration config)
  867. {
  868. var user = GetUserById(userId);
  869. return UpdateConfiguration(user, config, true);
  870. }
  871. private async Task UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  872. {
  873. var path = GetConfigurationFilePath(user);
  874. // The xml serializer will output differently if the type is not exact
  875. if (config.GetType() != typeof(UserConfiguration))
  876. {
  877. var json = _jsonSerializer.SerializeToString(config);
  878. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  879. }
  880. Directory.CreateDirectory(Path.GetDirectoryName(path));
  881. lock (_configSyncLock)
  882. {
  883. _xmlSerializer.SerializeToFile(config, path);
  884. user.Configuration = config;
  885. }
  886. if (fireEvent)
  887. {
  888. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  889. }
  890. }
  891. }
  892. }