UserManager.cs 34 KB

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