UserManager.cs 35 KB

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