UserManager.cs 42 KB

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