UserManager.cs 34 KB

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