UserManager.cs 40 KB

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