UserManager.cs 40 KB

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