UserManager.cs 35 KB

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