UserManager.cs 35 KB

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