2
0

UserManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Connect;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Net;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Configuration;
  14. using MediaBrowser.Model.Connect;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Events;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Users;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Text;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using MediaBrowser.Model.Cryptography;
  30. using MediaBrowser.Model.IO;
  31. using MediaBrowser.Controller.Authentication;
  32. using MediaBrowser.Controller.Security;
  33. using MediaBrowser.Controller.Devices;
  34. using MediaBrowser.Controller.Session;
  35. using MediaBrowser.Controller.Plugins;
  36. namespace Emby.Server.Implementations.Library
  37. {
  38. /// <summary>
  39. /// Class UserManager
  40. /// </summary>
  41. public class UserManager : IUserManager
  42. {
  43. /// <summary>
  44. /// Gets the users.
  45. /// </summary>
  46. /// <value>The users.</value>
  47. public IEnumerable<User> Users { get { return _users; } }
  48. private User[] _users;
  49. /// <summary>
  50. /// The _logger
  51. /// </summary>
  52. private readonly ILogger _logger;
  53. /// <summary>
  54. /// Gets or sets the configuration manager.
  55. /// </summary>
  56. /// <value>The configuration manager.</value>
  57. private IServerConfigurationManager ConfigurationManager { get; set; }
  58. /// <summary>
  59. /// Gets the active user repository
  60. /// </summary>
  61. /// <value>The user repository.</value>
  62. private IUserRepository UserRepository { get; set; }
  63. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  64. private readonly IXmlSerializer _xmlSerializer;
  65. private readonly IJsonSerializer _jsonSerializer;
  66. private readonly INetworkManager _networkManager;
  67. private readonly Func<IImageProcessor> _imageProcessorFactory;
  68. private readonly Func<IDtoService> _dtoServiceFactory;
  69. private readonly IServerApplicationHost _appHost;
  70. private readonly IFileSystem _fileSystem;
  71. private readonly ICryptoProvider _cryptographyProvider;
  72. private IAuthenticationProvider[] _authenticationProviders;
  73. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  74. public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory, IServerApplicationHost appHost, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
  75. {
  76. _logger = logger;
  77. UserRepository = userRepository;
  78. _xmlSerializer = xmlSerializer;
  79. _networkManager = networkManager;
  80. _imageProcessorFactory = imageProcessorFactory;
  81. _dtoServiceFactory = dtoServiceFactory;
  82. _appHost = appHost;
  83. _jsonSerializer = jsonSerializer;
  84. _fileSystem = fileSystem;
  85. _cryptographyProvider = cryptographyProvider;
  86. ConfigurationManager = configurationManager;
  87. _users = Array.Empty<User>();
  88. DeletePinFile();
  89. }
  90. public NameIdPair[] GetAuthenticationProviders()
  91. {
  92. return _authenticationProviders
  93. .Where(i => i.IsEnabled)
  94. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  95. .ThenBy(i => i.Name)
  96. .Select(i => new NameIdPair
  97. {
  98. Name = i.Name,
  99. Id = GetAuthenticationProviderId(i)
  100. })
  101. .ToArray();
  102. }
  103. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders)
  104. {
  105. _authenticationProviders = authenticationProviders.ToArray();
  106. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  107. }
  108. #region UserUpdated Event
  109. /// <summary>
  110. /// Occurs when [user updated].
  111. /// </summary>
  112. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  113. public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
  114. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  115. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  116. /// <summary>
  117. /// Called when [user updated].
  118. /// </summary>
  119. /// <param name="user">The user.</param>
  120. private void OnUserUpdated(User user)
  121. {
  122. EventHelper.FireEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  123. }
  124. #endregion
  125. #region UserDeleted Event
  126. /// <summary>
  127. /// Occurs when [user deleted].
  128. /// </summary>
  129. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  130. /// <summary>
  131. /// Called when [user deleted].
  132. /// </summary>
  133. /// <param name="user">The user.</param>
  134. private void OnUserDeleted(User user)
  135. {
  136. EventHelper.FireEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  137. }
  138. #endregion
  139. /// <summary>
  140. /// Gets a User by Id
  141. /// </summary>
  142. /// <param name="id">The id.</param>
  143. /// <returns>User.</returns>
  144. /// <exception cref="System.ArgumentNullException"></exception>
  145. public User GetUserById(Guid id)
  146. {
  147. if (id.Equals(Guid.Empty))
  148. {
  149. throw new ArgumentNullException("id");
  150. }
  151. return Users.FirstOrDefault(u => u.Id == id);
  152. }
  153. /// <summary>
  154. /// Gets the user by identifier.
  155. /// </summary>
  156. /// <param name="id">The identifier.</param>
  157. /// <returns>User.</returns>
  158. public User GetUserById(string id)
  159. {
  160. return GetUserById(new Guid(id));
  161. }
  162. public User GetUserByName(string name)
  163. {
  164. if (string.IsNullOrWhiteSpace(name))
  165. {
  166. throw new ArgumentNullException("name");
  167. }
  168. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  169. }
  170. public void Initialize()
  171. {
  172. _users = LoadUsers();
  173. var users = Users.ToList();
  174. // If there are no local users with admin rights, make them all admins
  175. if (!users.Any(i => i.Policy.IsAdministrator))
  176. {
  177. foreach (var user in users)
  178. {
  179. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value == UserLinkType.LinkedUser)
  180. {
  181. user.Policy.IsAdministrator = true;
  182. UpdateUserPolicy(user, user.Policy, false);
  183. }
  184. }
  185. }
  186. }
  187. public bool IsValidUsername(string username)
  188. {
  189. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  190. foreach (var currentChar in username)
  191. {
  192. if (!IsValidUsernameCharacter(currentChar))
  193. {
  194. return false;
  195. }
  196. }
  197. return true;
  198. }
  199. private bool IsValidUsernameCharacter(char i)
  200. {
  201. return !char.Equals(i, '<') && !char.Equals(i, '>');
  202. }
  203. public string MakeValidUsername(string username)
  204. {
  205. if (IsValidUsername(username))
  206. {
  207. return username;
  208. }
  209. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  210. var builder = new StringBuilder();
  211. foreach (var c in username)
  212. {
  213. if (IsValidUsernameCharacter(c))
  214. {
  215. builder.Append(c);
  216. }
  217. }
  218. return builder.ToString();
  219. }
  220. public async Task<User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
  221. {
  222. if (string.IsNullOrWhiteSpace(username))
  223. {
  224. throw new ArgumentNullException("username");
  225. }
  226. var user = Users
  227. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  228. var success = false;
  229. IAuthenticationProvider authenticationProvider = null;
  230. if (user != null)
  231. {
  232. // Authenticate using local credentials if not a guest
  233. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  234. {
  235. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  236. authenticationProvider = authResult.Item1;
  237. success = authResult.Item2;
  238. }
  239. }
  240. else
  241. {
  242. // user is null
  243. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  244. authenticationProvider = authResult.Item1;
  245. success = authResult.Item2;
  246. if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
  247. {
  248. user = await CreateUser(username).ConfigureAwait(false);
  249. var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy;
  250. if (hasNewUserPolicy != null)
  251. {
  252. var policy = hasNewUserPolicy.GetNewUserPolicy();
  253. UpdateUserPolicy(user, policy, true);
  254. }
  255. }
  256. }
  257. if (success && user != null && authenticationProvider != null)
  258. {
  259. var providerId = GetAuthenticationProviderId(authenticationProvider);
  260. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  261. {
  262. user.Policy.AuthenticationProviderId = providerId;
  263. UpdateUserPolicy(user, user.Policy, true);
  264. }
  265. }
  266. if (user == null)
  267. {
  268. throw new SecurityException("Invalid username or password entered.");
  269. }
  270. if (user.Policy.IsDisabled)
  271. {
  272. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  273. }
  274. if (user != null)
  275. {
  276. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  277. {
  278. throw new SecurityException("Forbidden.");
  279. }
  280. if (!user.IsParentalScheduleAllowed())
  281. {
  282. throw new SecurityException("User is not allowed access at this time.");
  283. }
  284. }
  285. // Update LastActivityDate and LastLoginDate, then save
  286. if (success)
  287. {
  288. if (isUserSession)
  289. {
  290. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  291. UpdateUser(user);
  292. }
  293. UpdateInvalidLoginAttemptCount(user, 0);
  294. }
  295. else
  296. {
  297. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  298. }
  299. _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  300. return success ? user : null;
  301. }
  302. private string GetAuthenticationProviderId(IAuthenticationProvider provider)
  303. {
  304. return provider.GetType().FullName;
  305. }
  306. private IAuthenticationProvider GetAuthenticationProvider(User user)
  307. {
  308. return GetAuthenticationProviders(user).First();
  309. }
  310. private IAuthenticationProvider[] GetAuthenticationProviders(User user)
  311. {
  312. var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
  313. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  314. if (!string.IsNullOrEmpty(authenticationProviderId))
  315. {
  316. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  317. }
  318. if (providers.Length == 0)
  319. {
  320. providers = new IAuthenticationProvider[] { _defaultAuthenticationProvider };
  321. }
  322. return providers;
  323. }
  324. private async Task<bool> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
  325. {
  326. try
  327. {
  328. var requiresResolvedUser = provider as IRequiresResolvedUser;
  329. if (requiresResolvedUser != null)
  330. {
  331. await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
  332. }
  333. else
  334. {
  335. await provider.Authenticate(username, password).ConfigureAwait(false);
  336. }
  337. return true;
  338. }
  339. catch (Exception ex)
  340. {
  341. _logger.ErrorException("Error authenticating with provider {0}", ex, provider.Name);
  342. return false;
  343. }
  344. }
  345. private async Task<Tuple<IAuthenticationProvider, bool>> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
  346. {
  347. bool success = false;
  348. IAuthenticationProvider authenticationProvider = null;
  349. if (password != null && user != null)
  350. {
  351. // Doesn't look like this is even possible to be used, because of password == null checks below
  352. hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
  353. }
  354. if (password == null)
  355. {
  356. // legacy
  357. success = string.Equals(_defaultAuthenticationProvider.GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  358. }
  359. else
  360. {
  361. foreach (var provider in GetAuthenticationProviders(user))
  362. {
  363. success = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  364. if (success)
  365. {
  366. authenticationProvider = provider;
  367. break;
  368. }
  369. }
  370. }
  371. if (user != null)
  372. {
  373. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  374. {
  375. if (password == null)
  376. {
  377. // legacy
  378. success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  379. }
  380. else
  381. {
  382. success = string.Equals(GetLocalPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  383. }
  384. }
  385. }
  386. return new Tuple<IAuthenticationProvider, bool>(authenticationProvider, success);
  387. }
  388. private void UpdateInvalidLoginAttemptCount(User user, int newValue)
  389. {
  390. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  391. {
  392. user.Policy.InvalidLoginAttemptCount = newValue;
  393. var maxCount = user.Policy.IsAdministrator ?
  394. 3 :
  395. 5;
  396. var fireLockout = false;
  397. if (newValue >= maxCount)
  398. {
  399. //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  400. //user.Policy.IsDisabled = true;
  401. //fireLockout = true;
  402. }
  403. UpdateUserPolicy(user, user.Policy, false);
  404. if (fireLockout)
  405. {
  406. if (UserLockedOut != null)
  407. {
  408. EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
  409. }
  410. }
  411. }
  412. }
  413. private string GetLocalPasswordHash(User user)
  414. {
  415. return string.IsNullOrEmpty(user.EasyPassword)
  416. ? _defaultAuthenticationProvider.GetEmptyHashedString(user)
  417. : user.EasyPassword;
  418. }
  419. private bool IsPasswordEmpty(User user, string passwordHash)
  420. {
  421. return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
  422. }
  423. /// <summary>
  424. /// Loads the users from the repository
  425. /// </summary>
  426. /// <returns>IEnumerable{User}.</returns>
  427. private User[] LoadUsers()
  428. {
  429. var users = UserRepository.RetrieveAllUsers();
  430. // There always has to be at least one user.
  431. if (users.Count == 0)
  432. {
  433. var defaultName = Environment.UserName;
  434. if (string.IsNullOrWhiteSpace(defaultName))
  435. {
  436. defaultName = "MyJellyfinUser";
  437. }
  438. var name = MakeValidUsername(defaultName);
  439. var user = InstantiateNewUser(name);
  440. user.DateLastSaved = DateTime.UtcNow;
  441. UserRepository.CreateUser(user);
  442. users.Add(user);
  443. user.Policy.IsAdministrator = true;
  444. user.Policy.EnableContentDeletion = true;
  445. user.Policy.EnableRemoteControlOfOtherUsers = true;
  446. UpdateUserPolicy(user, user.Policy, false);
  447. }
  448. return users.ToArray();
  449. }
  450. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  451. {
  452. if (user == null)
  453. {
  454. throw new ArgumentNullException("user");
  455. }
  456. var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
  457. var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
  458. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  459. hasConfiguredEasyPassword :
  460. hasConfiguredPassword;
  461. var dto = new UserDto
  462. {
  463. Id = user.Id,
  464. Name = user.Name,
  465. HasPassword = hasPassword,
  466. HasConfiguredPassword = hasConfiguredPassword,
  467. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  468. LastActivityDate = user.LastActivityDate,
  469. LastLoginDate = user.LastLoginDate,
  470. Configuration = user.Configuration,
  471. ConnectLinkType = user.ConnectLinkType,
  472. ConnectUserId = user.ConnectUserId,
  473. ConnectUserName = user.ConnectUserName,
  474. ServerId = _appHost.SystemId,
  475. Policy = user.Policy
  476. };
  477. if (!hasPassword && Users.Count() == 1)
  478. {
  479. dto.EnableAutoLogin = true;
  480. }
  481. var image = user.GetImageInfo(ImageType.Primary, 0);
  482. if (image != null)
  483. {
  484. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  485. try
  486. {
  487. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  488. }
  489. catch (Exception ex)
  490. {
  491. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  492. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  493. }
  494. }
  495. return dto;
  496. }
  497. public UserDto GetOfflineUserDto(User user)
  498. {
  499. var dto = GetUserDto(user);
  500. dto.ServerName = _appHost.FriendlyName;
  501. return dto;
  502. }
  503. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  504. {
  505. try
  506. {
  507. return _imageProcessorFactory().GetImageCacheTag(item, image);
  508. }
  509. catch (Exception ex)
  510. {
  511. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  512. return null;
  513. }
  514. }
  515. /// <summary>
  516. /// Refreshes metadata for each user
  517. /// </summary>
  518. /// <param name="cancellationToken">The cancellation token.</param>
  519. /// <returns>Task.</returns>
  520. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  521. {
  522. foreach (var user in Users)
  523. {
  524. await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
  525. }
  526. }
  527. /// <summary>
  528. /// Renames the user.
  529. /// </summary>
  530. /// <param name="user">The user.</param>
  531. /// <param name="newName">The new name.</param>
  532. /// <returns>Task.</returns>
  533. /// <exception cref="System.ArgumentNullException">user</exception>
  534. /// <exception cref="System.ArgumentException"></exception>
  535. public async Task RenameUser(User user, string newName)
  536. {
  537. if (user == null)
  538. {
  539. throw new ArgumentNullException("user");
  540. }
  541. if (string.IsNullOrEmpty(newName))
  542. {
  543. throw new ArgumentNullException("newName");
  544. }
  545. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  546. {
  547. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  548. }
  549. if (user.Name.Equals(newName, StringComparison.Ordinal))
  550. {
  551. throw new ArgumentException("The new and old names must be different.");
  552. }
  553. await user.Rename(newName);
  554. OnUserUpdated(user);
  555. }
  556. /// <summary>
  557. /// Updates the user.
  558. /// </summary>
  559. /// <param name="user">The user.</param>
  560. /// <exception cref="System.ArgumentNullException">user</exception>
  561. /// <exception cref="System.ArgumentException"></exception>
  562. public void UpdateUser(User user)
  563. {
  564. if (user == null)
  565. {
  566. throw new ArgumentNullException("user");
  567. }
  568. if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
  569. {
  570. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  571. }
  572. user.DateModified = DateTime.UtcNow;
  573. user.DateLastSaved = DateTime.UtcNow;
  574. UserRepository.UpdateUser(user);
  575. OnUserUpdated(user);
  576. }
  577. public event EventHandler<GenericEventArgs<User>> UserCreated;
  578. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  579. /// <summary>
  580. /// Creates the user.
  581. /// </summary>
  582. /// <param name="name">The name.</param>
  583. /// <returns>User.</returns>
  584. /// <exception cref="System.ArgumentNullException">name</exception>
  585. /// <exception cref="System.ArgumentException"></exception>
  586. public async Task<User> CreateUser(string name)
  587. {
  588. if (string.IsNullOrWhiteSpace(name))
  589. {
  590. throw new ArgumentNullException("name");
  591. }
  592. if (!IsValidUsername(name))
  593. {
  594. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  595. }
  596. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  597. {
  598. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  599. }
  600. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  601. try
  602. {
  603. var user = InstantiateNewUser(name);
  604. var list = Users.ToList();
  605. list.Add(user);
  606. _users = list.ToArray();
  607. user.DateLastSaved = DateTime.UtcNow;
  608. UserRepository.CreateUser(user);
  609. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  610. return user;
  611. }
  612. finally
  613. {
  614. _userListLock.Release();
  615. }
  616. }
  617. /// <summary>
  618. /// Deletes the user.
  619. /// </summary>
  620. /// <param name="user">The user.</param>
  621. /// <returns>Task.</returns>
  622. /// <exception cref="System.ArgumentNullException">user</exception>
  623. /// <exception cref="System.ArgumentException"></exception>
  624. public async Task DeleteUser(User user)
  625. {
  626. if (user == null)
  627. {
  628. throw new ArgumentNullException("user");
  629. }
  630. var allUsers = Users.ToList();
  631. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  632. {
  633. 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));
  634. }
  635. if (allUsers.Count == 1)
  636. {
  637. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  638. }
  639. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  640. {
  641. 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));
  642. }
  643. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  644. try
  645. {
  646. var configPath = GetConfigurationFilePath(user);
  647. UserRepository.DeleteUser(user);
  648. try
  649. {
  650. _fileSystem.DeleteFile(configPath);
  651. }
  652. catch (IOException ex)
  653. {
  654. _logger.ErrorException("Error deleting file {0}", ex, configPath);
  655. }
  656. DeleteUserPolicy(user);
  657. _users = allUsers.Where(i => i.Id != user.Id).ToArray();
  658. OnUserDeleted(user);
  659. }
  660. finally
  661. {
  662. _userListLock.Release();
  663. }
  664. }
  665. /// <summary>
  666. /// Resets the password by clearing it.
  667. /// </summary>
  668. /// <returns>Task.</returns>
  669. public Task ResetPassword(User user)
  670. {
  671. return ChangePassword(user, string.Empty);
  672. }
  673. public void ResetEasyPassword(User user)
  674. {
  675. ChangeEasyPassword(user, string.Empty, null);
  676. }
  677. public async Task ChangePassword(User user, string newPassword)
  678. {
  679. if (user == null)
  680. {
  681. throw new ArgumentNullException("user");
  682. }
  683. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  684. {
  685. throw new ArgumentException("Passwords for guests cannot be changed.");
  686. }
  687. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  688. UpdateUser(user);
  689. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  690. }
  691. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  692. {
  693. if (user == null)
  694. {
  695. throw new ArgumentNullException("user");
  696. }
  697. if (newPassword != null)
  698. {
  699. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  700. }
  701. if (string.IsNullOrWhiteSpace(newPasswordHash))
  702. {
  703. throw new ArgumentNullException("newPasswordHash");
  704. }
  705. user.EasyPassword = newPasswordHash;
  706. UpdateUser(user);
  707. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  708. }
  709. /// <summary>
  710. /// Instantiates the new user.
  711. /// </summary>
  712. /// <param name="name">The name.</param>
  713. /// <returns>User.</returns>
  714. private User InstantiateNewUser(string name)
  715. {
  716. return new User
  717. {
  718. Name = name,
  719. Id = Guid.NewGuid(),
  720. DateCreated = DateTime.UtcNow,
  721. DateModified = DateTime.UtcNow,
  722. UsesIdForConfigurationPath = true,
  723. //Salt = BCrypt.GenerateSalt()
  724. };
  725. }
  726. private string PasswordResetFile
  727. {
  728. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  729. }
  730. private string _lastPin;
  731. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  732. private int _pinAttempts;
  733. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  734. {
  735. var num = new Random().Next(1, 9999);
  736. var path = PasswordResetFile;
  737. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  738. _lastPin = pin;
  739. var time = TimeSpan.FromMinutes(5);
  740. var expiration = DateTime.UtcNow.Add(time);
  741. var text = new StringBuilder();
  742. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  743. text.AppendLine("Use your web browser to visit:");
  744. text.AppendLine(string.Empty);
  745. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  746. text.AppendLine(string.Empty);
  747. text.AppendLine("Enter the following pin code:");
  748. text.AppendLine(string.Empty);
  749. text.AppendLine(pin);
  750. text.AppendLine(string.Empty);
  751. var localExpirationTime = expiration.ToLocalTime();
  752. // Tuesday, 22 August 2006 06:30 AM
  753. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  754. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  755. var result = new PasswordPinCreationResult
  756. {
  757. PinFile = path,
  758. ExpirationDate = expiration
  759. };
  760. _lastPasswordPinCreationResult = result;
  761. _pinAttempts = 0;
  762. return result;
  763. }
  764. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  765. {
  766. DeletePinFile();
  767. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  768. null :
  769. GetUserByName(enteredUsername);
  770. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  771. {
  772. throw new ArgumentException("Unable to process forgot password request for guests.");
  773. }
  774. var action = ForgotPasswordAction.InNetworkRequired;
  775. string pinFile = null;
  776. DateTime? expirationDate = null;
  777. if (user != null && !user.Policy.IsAdministrator)
  778. {
  779. action = ForgotPasswordAction.ContactAdmin;
  780. }
  781. else
  782. {
  783. if (isInNetwork)
  784. {
  785. action = ForgotPasswordAction.PinCode;
  786. }
  787. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  788. pinFile = result.PinFile;
  789. expirationDate = result.ExpirationDate;
  790. }
  791. return new ForgotPasswordResult
  792. {
  793. Action = action,
  794. PinFile = pinFile,
  795. PinExpirationDate = expirationDate
  796. };
  797. }
  798. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  799. {
  800. DeletePinFile();
  801. var usersReset = new List<string>();
  802. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  803. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  804. _lastPasswordPinCreationResult != null &&
  805. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  806. if (valid)
  807. {
  808. _lastPin = null;
  809. _lastPasswordPinCreationResult = null;
  810. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  811. .ToList();
  812. foreach (var user in users)
  813. {
  814. await ResetPassword(user).ConfigureAwait(false);
  815. if (user.Policy.IsDisabled)
  816. {
  817. user.Policy.IsDisabled = false;
  818. UpdateUserPolicy(user, user.Policy, true);
  819. }
  820. usersReset.Add(user.Name);
  821. }
  822. }
  823. else
  824. {
  825. _pinAttempts++;
  826. if (_pinAttempts >= 3)
  827. {
  828. _lastPin = null;
  829. _lastPasswordPinCreationResult = null;
  830. }
  831. }
  832. return new PinRedeemResult
  833. {
  834. Success = valid,
  835. UsersReset = usersReset.ToArray()
  836. };
  837. }
  838. private void DeletePinFile()
  839. {
  840. try
  841. {
  842. _fileSystem.DeleteFile(PasswordResetFile);
  843. }
  844. catch
  845. {
  846. }
  847. }
  848. class PasswordPinCreationResult
  849. {
  850. public string PinFile { get; set; }
  851. public DateTime ExpirationDate { get; set; }
  852. }
  853. public UserPolicy GetUserPolicy(User user)
  854. {
  855. var path = GetPolicyFilePath(user);
  856. try
  857. {
  858. lock (_policySyncLock)
  859. {
  860. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  861. }
  862. }
  863. catch (FileNotFoundException)
  864. {
  865. return GetDefaultPolicy(user);
  866. }
  867. catch (IOException)
  868. {
  869. return GetDefaultPolicy(user);
  870. }
  871. catch (Exception ex)
  872. {
  873. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  874. return GetDefaultPolicy(user);
  875. }
  876. }
  877. private UserPolicy GetDefaultPolicy(User user)
  878. {
  879. return new UserPolicy
  880. {
  881. EnableContentDownloading = true,
  882. EnableSyncTranscoding = true
  883. };
  884. }
  885. private readonly object _policySyncLock = new object();
  886. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  887. {
  888. var user = GetUserById(userId);
  889. UpdateUserPolicy(user, userPolicy, true);
  890. }
  891. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  892. {
  893. // The xml serializer will output differently if the type is not exact
  894. if (userPolicy.GetType() != typeof(UserPolicy))
  895. {
  896. var json = _jsonSerializer.SerializeToString(userPolicy);
  897. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  898. }
  899. var path = GetPolicyFilePath(user);
  900. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  901. lock (_policySyncLock)
  902. {
  903. _xmlSerializer.SerializeToFile(userPolicy, path);
  904. user.Policy = userPolicy;
  905. }
  906. if (fireEvent)
  907. {
  908. EventHelper.FireEventIfNotNull(UserPolicyUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  909. }
  910. }
  911. private void DeleteUserPolicy(User user)
  912. {
  913. var path = GetPolicyFilePath(user);
  914. try
  915. {
  916. lock (_policySyncLock)
  917. {
  918. _fileSystem.DeleteFile(path);
  919. }
  920. }
  921. catch (IOException)
  922. {
  923. }
  924. catch (Exception ex)
  925. {
  926. _logger.ErrorException("Error deleting policy file", ex);
  927. }
  928. }
  929. private string GetPolicyFilePath(User user)
  930. {
  931. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  932. }
  933. private string GetConfigurationFilePath(User user)
  934. {
  935. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  936. }
  937. public UserConfiguration GetUserConfiguration(User user)
  938. {
  939. var path = GetConfigurationFilePath(user);
  940. try
  941. {
  942. lock (_configSyncLock)
  943. {
  944. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  945. }
  946. }
  947. catch (FileNotFoundException)
  948. {
  949. return new UserConfiguration();
  950. }
  951. catch (IOException)
  952. {
  953. return new UserConfiguration();
  954. }
  955. catch (Exception ex)
  956. {
  957. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  958. return new UserConfiguration();
  959. }
  960. }
  961. private readonly object _configSyncLock = new object();
  962. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  963. {
  964. var user = GetUserById(userId);
  965. UpdateConfiguration(user, config);
  966. }
  967. public void UpdateConfiguration(User user, UserConfiguration config)
  968. {
  969. UpdateConfiguration(user, config, true);
  970. }
  971. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  972. {
  973. var path = GetConfigurationFilePath(user);
  974. // The xml serializer will output differently if the type is not exact
  975. if (config.GetType() != typeof(UserConfiguration))
  976. {
  977. var json = _jsonSerializer.SerializeToString(config);
  978. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  979. }
  980. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  981. lock (_configSyncLock)
  982. {
  983. _xmlSerializer.SerializeToFile(config, path);
  984. user.Configuration = config;
  985. }
  986. if (fireEvent)
  987. {
  988. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  989. }
  990. }
  991. }
  992. public class DeviceAccessEntryPoint : IServerEntryPoint
  993. {
  994. private IUserManager _userManager;
  995. private IAuthenticationRepository _authRepo;
  996. private IDeviceManager _deviceManager;
  997. private ISessionManager _sessionManager;
  998. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  999. {
  1000. _userManager = userManager;
  1001. _authRepo = authRepo;
  1002. _deviceManager = deviceManager;
  1003. _sessionManager = sessionManager;
  1004. }
  1005. public void Run()
  1006. {
  1007. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  1008. }
  1009. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  1010. {
  1011. var user = e.Argument;
  1012. if (!user.Policy.EnableAllDevices)
  1013. {
  1014. UpdateDeviceAccess(user);
  1015. }
  1016. }
  1017. private void UpdateDeviceAccess(User user)
  1018. {
  1019. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1020. {
  1021. UserId = user.Id
  1022. }).Items;
  1023. foreach (var authInfo in existing)
  1024. {
  1025. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  1026. {
  1027. _sessionManager.Logout(authInfo);
  1028. }
  1029. }
  1030. }
  1031. public void Dispose()
  1032. {
  1033. }
  1034. }
  1035. }