UserManager.cs 42 KB

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