UserManager.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. // Maybe user accidently entered connect credentials. let's be flexible
  242. if (!success && user.ConnectLinkType.HasValue && !string.IsNullOrWhiteSpace(user.ConnectUserName))
  243. {
  244. try
  245. {
  246. await _connectFactory().Authenticate(user.ConnectUserName, password).ConfigureAwait(false);
  247. success = true;
  248. }
  249. catch
  250. {
  251. }
  252. }
  253. }
  254. else
  255. {
  256. // user is null
  257. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  258. authenticationProvider = authResult.Item1;
  259. success = authResult.Item2;
  260. if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
  261. {
  262. user = await CreateUser(username).ConfigureAwait(false);
  263. var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy;
  264. if (hasNewUserPolicy != null)
  265. {
  266. var policy = hasNewUserPolicy.GetNewUserPolicy();
  267. UpdateUserPolicy(user, policy, true);
  268. }
  269. }
  270. }
  271. if (success && user != null && authenticationProvider != null)
  272. {
  273. var providerId = GetAuthenticationProviderId(authenticationProvider);
  274. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  275. {
  276. user.Policy.AuthenticationProviderId = providerId;
  277. UpdateUserPolicy(user, user.Policy, true);
  278. }
  279. }
  280. // Try originally entered username
  281. if (!success && (user == null || !string.Equals(user.ConnectUserName, username, StringComparison.OrdinalIgnoreCase)))
  282. {
  283. try
  284. {
  285. var connectAuthResult = await _connectFactory().Authenticate(username, password).ConfigureAwait(false);
  286. user = Users.FirstOrDefault(i => string.Equals(i.ConnectUserId, connectAuthResult.User.Id, StringComparison.OrdinalIgnoreCase));
  287. success = user != null;
  288. }
  289. catch
  290. {
  291. }
  292. }
  293. if (user == null)
  294. {
  295. throw new SecurityException("Invalid username or password entered.");
  296. }
  297. if (user.Policy.IsDisabled)
  298. {
  299. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  300. }
  301. if (user != null)
  302. {
  303. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  304. {
  305. throw new SecurityException("Forbidden.");
  306. }
  307. if (!user.IsParentalScheduleAllowed())
  308. {
  309. throw new SecurityException("User is not allowed access at this time.");
  310. }
  311. }
  312. // Update LastActivityDate and LastLoginDate, then save
  313. if (success)
  314. {
  315. if (isUserSession)
  316. {
  317. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  318. UpdateUser(user);
  319. }
  320. UpdateInvalidLoginAttemptCount(user, 0);
  321. }
  322. else
  323. {
  324. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  325. }
  326. _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  327. return success ? user : null;
  328. }
  329. private string GetAuthenticationProviderId(IAuthenticationProvider provider)
  330. {
  331. return provider.GetType().FullName;
  332. }
  333. private IAuthenticationProvider GetAuthenticationProvider(User user)
  334. {
  335. return GetAuthenticationProviders(user).First();
  336. }
  337. private IAuthenticationProvider[] GetAuthenticationProviders(User user)
  338. {
  339. var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
  340. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  341. if (!string.IsNullOrEmpty(authenticationProviderId))
  342. {
  343. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  344. }
  345. if (providers.Length == 0)
  346. {
  347. providers = new IAuthenticationProvider[] { _defaultAuthenticationProvider };
  348. }
  349. return providers;
  350. }
  351. private async Task<bool> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
  352. {
  353. try
  354. {
  355. var requiresResolvedUser = provider as IRequiresResolvedUser;
  356. if (requiresResolvedUser != null)
  357. {
  358. await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
  359. }
  360. else
  361. {
  362. await provider.Authenticate(username, password).ConfigureAwait(false);
  363. }
  364. return true;
  365. }
  366. catch (Exception ex)
  367. {
  368. _logger.ErrorException("Error authenticating with provider {0}", ex, provider.Name);
  369. return false;
  370. }
  371. }
  372. private async Task<Tuple<IAuthenticationProvider, bool>> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
  373. {
  374. bool success = false;
  375. IAuthenticationProvider authenticationProvider = null;
  376. if (password != null && user != null)
  377. {
  378. // Doesn't look like this is even possible to be used, because of password == null checks below
  379. hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
  380. }
  381. if (password == null)
  382. {
  383. // legacy
  384. success = string.Equals(_defaultAuthenticationProvider.GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  385. }
  386. else
  387. {
  388. foreach (var provider in GetAuthenticationProviders(user))
  389. {
  390. success = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  391. if (success)
  392. {
  393. authenticationProvider = provider;
  394. break;
  395. }
  396. }
  397. }
  398. if (user != null)
  399. {
  400. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  401. {
  402. if (password == null)
  403. {
  404. // legacy
  405. success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  406. }
  407. else
  408. {
  409. success = string.Equals(GetLocalPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  410. }
  411. }
  412. }
  413. return new Tuple<IAuthenticationProvider, bool>(authenticationProvider, success);
  414. }
  415. private void UpdateInvalidLoginAttemptCount(User user, int newValue)
  416. {
  417. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  418. {
  419. user.Policy.InvalidLoginAttemptCount = newValue;
  420. var maxCount = user.Policy.IsAdministrator ?
  421. 3 :
  422. 5;
  423. var fireLockout = false;
  424. if (newValue >= maxCount)
  425. {
  426. //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  427. //user.Policy.IsDisabled = true;
  428. //fireLockout = true;
  429. }
  430. UpdateUserPolicy(user, user.Policy, false);
  431. if (fireLockout)
  432. {
  433. if (UserLockedOut != null)
  434. {
  435. EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
  436. }
  437. }
  438. }
  439. }
  440. private string GetLocalPasswordHash(User user)
  441. {
  442. return string.IsNullOrEmpty(user.EasyPassword)
  443. ? _defaultAuthenticationProvider.GetEmptyHashedString(user)
  444. : user.EasyPassword;
  445. }
  446. private bool IsPasswordEmpty(User user, string passwordHash)
  447. {
  448. return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
  449. }
  450. /// <summary>
  451. /// Loads the users from the repository
  452. /// </summary>
  453. /// <returns>IEnumerable{User}.</returns>
  454. private User[] LoadUsers()
  455. {
  456. var users = UserRepository.RetrieveAllUsers();
  457. // There always has to be at least one user.
  458. if (users.Count == 0)
  459. {
  460. var defaultName = Environment.UserName;
  461. if (string.IsNullOrWhiteSpace(defaultName))
  462. {
  463. defaultName = "MyEmbyUser";
  464. }
  465. var name = MakeValidUsername(defaultName);
  466. var user = InstantiateNewUser(name);
  467. user.DateLastSaved = DateTime.UtcNow;
  468. UserRepository.CreateUser(user);
  469. users.Add(user);
  470. user.Policy.IsAdministrator = true;
  471. user.Policy.EnableContentDeletion = true;
  472. user.Policy.EnableRemoteControlOfOtherUsers = true;
  473. UpdateUserPolicy(user, user.Policy, false);
  474. }
  475. return users.ToArray();
  476. }
  477. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  478. {
  479. if (user == null)
  480. {
  481. throw new ArgumentNullException("user");
  482. }
  483. var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
  484. var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
  485. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  486. hasConfiguredEasyPassword :
  487. hasConfiguredPassword;
  488. var dto = new UserDto
  489. {
  490. Id = user.Id,
  491. Name = user.Name,
  492. HasPassword = hasPassword,
  493. HasConfiguredPassword = hasConfiguredPassword,
  494. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  495. LastActivityDate = user.LastActivityDate,
  496. LastLoginDate = user.LastLoginDate,
  497. Configuration = user.Configuration,
  498. ConnectLinkType = user.ConnectLinkType,
  499. ConnectUserId = user.ConnectUserId,
  500. ConnectUserName = user.ConnectUserName,
  501. ServerId = _appHost.SystemId,
  502. Policy = user.Policy
  503. };
  504. if (!hasPassword && Users.Count() == 1)
  505. {
  506. dto.EnableAutoLogin = true;
  507. }
  508. var image = user.GetImageInfo(ImageType.Primary, 0);
  509. if (image != null)
  510. {
  511. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  512. try
  513. {
  514. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  515. }
  516. catch (Exception ex)
  517. {
  518. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  519. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  520. }
  521. }
  522. return dto;
  523. }
  524. public UserDto GetOfflineUserDto(User user)
  525. {
  526. var dto = GetUserDto(user);
  527. dto.ServerName = _appHost.FriendlyName;
  528. return dto;
  529. }
  530. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  531. {
  532. try
  533. {
  534. return _imageProcessorFactory().GetImageCacheTag(item, image);
  535. }
  536. catch (Exception ex)
  537. {
  538. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  539. return null;
  540. }
  541. }
  542. /// <summary>
  543. /// Refreshes metadata for each user
  544. /// </summary>
  545. /// <param name="cancellationToken">The cancellation token.</param>
  546. /// <returns>Task.</returns>
  547. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  548. {
  549. foreach (var user in Users)
  550. {
  551. await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
  552. }
  553. }
  554. /// <summary>
  555. /// Renames the user.
  556. /// </summary>
  557. /// <param name="user">The user.</param>
  558. /// <param name="newName">The new name.</param>
  559. /// <returns>Task.</returns>
  560. /// <exception cref="System.ArgumentNullException">user</exception>
  561. /// <exception cref="System.ArgumentException"></exception>
  562. public async Task RenameUser(User user, string newName)
  563. {
  564. if (user == null)
  565. {
  566. throw new ArgumentNullException("user");
  567. }
  568. if (string.IsNullOrEmpty(newName))
  569. {
  570. throw new ArgumentNullException("newName");
  571. }
  572. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  573. {
  574. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  575. }
  576. if (user.Name.Equals(newName, StringComparison.Ordinal))
  577. {
  578. throw new ArgumentException("The new and old names must be different.");
  579. }
  580. await user.Rename(newName);
  581. OnUserUpdated(user);
  582. }
  583. /// <summary>
  584. /// Updates the user.
  585. /// </summary>
  586. /// <param name="user">The user.</param>
  587. /// <exception cref="System.ArgumentNullException">user</exception>
  588. /// <exception cref="System.ArgumentException"></exception>
  589. public void UpdateUser(User user)
  590. {
  591. if (user == null)
  592. {
  593. throw new ArgumentNullException("user");
  594. }
  595. if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
  596. {
  597. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  598. }
  599. user.DateModified = DateTime.UtcNow;
  600. user.DateLastSaved = DateTime.UtcNow;
  601. UserRepository.UpdateUser(user);
  602. OnUserUpdated(user);
  603. }
  604. public event EventHandler<GenericEventArgs<User>> UserCreated;
  605. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  606. /// <summary>
  607. /// Creates the user.
  608. /// </summary>
  609. /// <param name="name">The name.</param>
  610. /// <returns>User.</returns>
  611. /// <exception cref="System.ArgumentNullException">name</exception>
  612. /// <exception cref="System.ArgumentException"></exception>
  613. public async Task<User> CreateUser(string name)
  614. {
  615. if (string.IsNullOrWhiteSpace(name))
  616. {
  617. throw new ArgumentNullException("name");
  618. }
  619. if (!IsValidUsername(name))
  620. {
  621. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  622. }
  623. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  624. {
  625. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  626. }
  627. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  628. try
  629. {
  630. var user = InstantiateNewUser(name);
  631. var list = Users.ToList();
  632. list.Add(user);
  633. _users = list.ToArray();
  634. user.DateLastSaved = DateTime.UtcNow;
  635. UserRepository.CreateUser(user);
  636. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  637. return user;
  638. }
  639. finally
  640. {
  641. _userListLock.Release();
  642. }
  643. }
  644. /// <summary>
  645. /// Deletes the user.
  646. /// </summary>
  647. /// <param name="user">The user.</param>
  648. /// <returns>Task.</returns>
  649. /// <exception cref="System.ArgumentNullException">user</exception>
  650. /// <exception cref="System.ArgumentException"></exception>
  651. public async Task DeleteUser(User user)
  652. {
  653. if (user == null)
  654. {
  655. throw new ArgumentNullException("user");
  656. }
  657. if (user.ConnectLinkType.HasValue)
  658. {
  659. await _connectFactory().RemoveConnect(user).ConfigureAwait(false);
  660. }
  661. var allUsers = Users.ToList();
  662. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  663. {
  664. 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));
  665. }
  666. if (allUsers.Count == 1)
  667. {
  668. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  669. }
  670. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  671. {
  672. 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));
  673. }
  674. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  675. try
  676. {
  677. var configPath = GetConfigurationFilePath(user);
  678. UserRepository.DeleteUser(user);
  679. try
  680. {
  681. _fileSystem.DeleteFile(configPath);
  682. }
  683. catch (IOException ex)
  684. {
  685. _logger.ErrorException("Error deleting file {0}", ex, configPath);
  686. }
  687. DeleteUserPolicy(user);
  688. _users = allUsers.Where(i => i.Id != user.Id).ToArray();
  689. OnUserDeleted(user);
  690. }
  691. finally
  692. {
  693. _userListLock.Release();
  694. }
  695. }
  696. /// <summary>
  697. /// Resets the password by clearing it.
  698. /// </summary>
  699. /// <returns>Task.</returns>
  700. public Task ResetPassword(User user)
  701. {
  702. return ChangePassword(user, string.Empty);
  703. }
  704. public void ResetEasyPassword(User user)
  705. {
  706. ChangeEasyPassword(user, string.Empty, null);
  707. }
  708. public async Task ChangePassword(User user, string newPassword)
  709. {
  710. if (user == null)
  711. {
  712. throw new ArgumentNullException("user");
  713. }
  714. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  715. {
  716. throw new ArgumentException("Passwords for guests cannot be changed.");
  717. }
  718. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  719. UpdateUser(user);
  720. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  721. }
  722. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  723. {
  724. if (user == null)
  725. {
  726. throw new ArgumentNullException("user");
  727. }
  728. if (newPassword != null)
  729. {
  730. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  731. }
  732. if (string.IsNullOrWhiteSpace(newPasswordHash))
  733. {
  734. throw new ArgumentNullException("newPasswordHash");
  735. }
  736. user.EasyPassword = newPasswordHash;
  737. UpdateUser(user);
  738. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  739. }
  740. /// <summary>
  741. /// Instantiates the new user.
  742. /// </summary>
  743. /// <param name="name">The name.</param>
  744. /// <returns>User.</returns>
  745. private User InstantiateNewUser(string name)
  746. {
  747. return new User
  748. {
  749. Name = name,
  750. Id = Guid.NewGuid(),
  751. DateCreated = DateTime.UtcNow,
  752. DateModified = DateTime.UtcNow,
  753. UsesIdForConfigurationPath = true,
  754. //Salt = BCrypt.GenerateSalt()
  755. };
  756. }
  757. private string PasswordResetFile
  758. {
  759. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  760. }
  761. private string _lastPin;
  762. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  763. private int _pinAttempts;
  764. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  765. {
  766. var num = new Random().Next(1, 9999);
  767. var path = PasswordResetFile;
  768. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  769. _lastPin = pin;
  770. var time = TimeSpan.FromMinutes(5);
  771. var expiration = DateTime.UtcNow.Add(time);
  772. var text = new StringBuilder();
  773. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  774. text.AppendLine("Use your web browser to visit:");
  775. text.AppendLine(string.Empty);
  776. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  777. text.AppendLine(string.Empty);
  778. text.AppendLine("Enter the following pin code:");
  779. text.AppendLine(string.Empty);
  780. text.AppendLine(pin);
  781. text.AppendLine(string.Empty);
  782. var localExpirationTime = expiration.ToLocalTime();
  783. // Tuesday, 22 August 2006 06:30 AM
  784. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  785. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  786. var result = new PasswordPinCreationResult
  787. {
  788. PinFile = path,
  789. ExpirationDate = expiration
  790. };
  791. _lastPasswordPinCreationResult = result;
  792. _pinAttempts = 0;
  793. return result;
  794. }
  795. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  796. {
  797. DeletePinFile();
  798. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  799. null :
  800. GetUserByName(enteredUsername);
  801. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  802. {
  803. throw new ArgumentException("Unable to process forgot password request for guests.");
  804. }
  805. var action = ForgotPasswordAction.InNetworkRequired;
  806. string pinFile = null;
  807. DateTime? expirationDate = null;
  808. if (user != null && !user.Policy.IsAdministrator)
  809. {
  810. action = ForgotPasswordAction.ContactAdmin;
  811. }
  812. else
  813. {
  814. if (isInNetwork)
  815. {
  816. action = ForgotPasswordAction.PinCode;
  817. }
  818. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  819. pinFile = result.PinFile;
  820. expirationDate = result.ExpirationDate;
  821. }
  822. return new ForgotPasswordResult
  823. {
  824. Action = action,
  825. PinFile = pinFile,
  826. PinExpirationDate = expirationDate
  827. };
  828. }
  829. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  830. {
  831. DeletePinFile();
  832. var usersReset = new List<string>();
  833. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  834. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  835. _lastPasswordPinCreationResult != null &&
  836. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  837. if (valid)
  838. {
  839. _lastPin = null;
  840. _lastPasswordPinCreationResult = null;
  841. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  842. .ToList();
  843. foreach (var user in users)
  844. {
  845. await ResetPassword(user).ConfigureAwait(false);
  846. if (user.Policy.IsDisabled)
  847. {
  848. user.Policy.IsDisabled = false;
  849. UpdateUserPolicy(user, user.Policy, true);
  850. }
  851. usersReset.Add(user.Name);
  852. }
  853. }
  854. else
  855. {
  856. _pinAttempts++;
  857. if (_pinAttempts >= 3)
  858. {
  859. _lastPin = null;
  860. _lastPasswordPinCreationResult = null;
  861. }
  862. }
  863. return new PinRedeemResult
  864. {
  865. Success = valid,
  866. UsersReset = usersReset.ToArray()
  867. };
  868. }
  869. private void DeletePinFile()
  870. {
  871. try
  872. {
  873. _fileSystem.DeleteFile(PasswordResetFile);
  874. }
  875. catch
  876. {
  877. }
  878. }
  879. class PasswordPinCreationResult
  880. {
  881. public string PinFile { get; set; }
  882. public DateTime ExpirationDate { get; set; }
  883. }
  884. public UserPolicy GetUserPolicy(User user)
  885. {
  886. var path = GetPolicyFilePath(user);
  887. try
  888. {
  889. lock (_policySyncLock)
  890. {
  891. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  892. }
  893. }
  894. catch (FileNotFoundException)
  895. {
  896. return GetDefaultPolicy(user);
  897. }
  898. catch (IOException)
  899. {
  900. return GetDefaultPolicy(user);
  901. }
  902. catch (Exception ex)
  903. {
  904. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  905. return GetDefaultPolicy(user);
  906. }
  907. }
  908. private UserPolicy GetDefaultPolicy(User user)
  909. {
  910. return new UserPolicy
  911. {
  912. EnableContentDownloading = true,
  913. EnableSyncTranscoding = true
  914. };
  915. }
  916. private readonly object _policySyncLock = new object();
  917. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  918. {
  919. var user = GetUserById(userId);
  920. UpdateUserPolicy(user, userPolicy, true);
  921. }
  922. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  923. {
  924. // The xml serializer will output differently if the type is not exact
  925. if (userPolicy.GetType() != typeof(UserPolicy))
  926. {
  927. var json = _jsonSerializer.SerializeToString(userPolicy);
  928. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  929. }
  930. var path = GetPolicyFilePath(user);
  931. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  932. lock (_policySyncLock)
  933. {
  934. _xmlSerializer.SerializeToFile(userPolicy, path);
  935. user.Policy = userPolicy;
  936. }
  937. if (fireEvent)
  938. {
  939. EventHelper.FireEventIfNotNull(UserPolicyUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  940. }
  941. }
  942. private void DeleteUserPolicy(User user)
  943. {
  944. var path = GetPolicyFilePath(user);
  945. try
  946. {
  947. lock (_policySyncLock)
  948. {
  949. _fileSystem.DeleteFile(path);
  950. }
  951. }
  952. catch (IOException)
  953. {
  954. }
  955. catch (Exception ex)
  956. {
  957. _logger.ErrorException("Error deleting policy file", ex);
  958. }
  959. }
  960. private string GetPolicyFilePath(User user)
  961. {
  962. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  963. }
  964. private string GetConfigurationFilePath(User user)
  965. {
  966. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  967. }
  968. public UserConfiguration GetUserConfiguration(User user)
  969. {
  970. var path = GetConfigurationFilePath(user);
  971. try
  972. {
  973. lock (_configSyncLock)
  974. {
  975. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  976. }
  977. }
  978. catch (FileNotFoundException)
  979. {
  980. return new UserConfiguration();
  981. }
  982. catch (IOException)
  983. {
  984. return new UserConfiguration();
  985. }
  986. catch (Exception ex)
  987. {
  988. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  989. return new UserConfiguration();
  990. }
  991. }
  992. private readonly object _configSyncLock = new object();
  993. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  994. {
  995. var user = GetUserById(userId);
  996. UpdateConfiguration(user, config);
  997. }
  998. public void UpdateConfiguration(User user, UserConfiguration config)
  999. {
  1000. UpdateConfiguration(user, config, true);
  1001. }
  1002. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  1003. {
  1004. var path = GetConfigurationFilePath(user);
  1005. // The xml serializer will output differently if the type is not exact
  1006. if (config.GetType() != typeof(UserConfiguration))
  1007. {
  1008. var json = _jsonSerializer.SerializeToString(config);
  1009. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  1010. }
  1011. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  1012. lock (_configSyncLock)
  1013. {
  1014. _xmlSerializer.SerializeToFile(config, path);
  1015. user.Configuration = config;
  1016. }
  1017. if (fireEvent)
  1018. {
  1019. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  1020. }
  1021. }
  1022. }
  1023. public class DeviceAccessEntryPoint : IServerEntryPoint
  1024. {
  1025. private IUserManager _userManager;
  1026. private IAuthenticationRepository _authRepo;
  1027. private IDeviceManager _deviceManager;
  1028. private ISessionManager _sessionManager;
  1029. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  1030. {
  1031. _userManager = userManager;
  1032. _authRepo = authRepo;
  1033. _deviceManager = deviceManager;
  1034. _sessionManager = sessionManager;
  1035. }
  1036. public void Run()
  1037. {
  1038. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  1039. }
  1040. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  1041. {
  1042. var user = e.Argument;
  1043. if (!user.Policy.EnableAllDevices)
  1044. {
  1045. UpdateDeviceAccess(user);
  1046. }
  1047. }
  1048. private void UpdateDeviceAccess(User user)
  1049. {
  1050. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1051. {
  1052. UserId = user.Id
  1053. }).Items;
  1054. foreach (var authInfo in existing)
  1055. {
  1056. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  1057. {
  1058. _sessionManager.Logout(authInfo);
  1059. }
  1060. }
  1061. }
  1062. public void Dispose()
  1063. {
  1064. }
  1065. }
  1066. }