UserManager.cs 33 KB

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