UserManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Events;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Serialization;
  17. using MediaBrowser.Server.Implementations.Security;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Security.Cryptography;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. namespace MediaBrowser.Server.Implementations.Library
  27. {
  28. /// <summary>
  29. /// Class UserManager
  30. /// </summary>
  31. public class UserManager : IUserManager
  32. {
  33. /// <summary>
  34. /// Gets the users.
  35. /// </summary>
  36. /// <value>The users.</value>
  37. public IEnumerable<User> Users { get; private set; }
  38. /// <summary>
  39. /// The _logger
  40. /// </summary>
  41. private readonly ILogger _logger;
  42. /// <summary>
  43. /// Gets or sets the configuration manager.
  44. /// </summary>
  45. /// <value>The configuration manager.</value>
  46. private IServerConfigurationManager ConfigurationManager { get; set; }
  47. /// <summary>
  48. /// Gets the active user repository
  49. /// </summary>
  50. /// <value>The user repository.</value>
  51. private IUserRepository UserRepository { get; set; }
  52. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  53. private readonly IXmlSerializer _xmlSerializer;
  54. private readonly INetworkManager _networkManager;
  55. private readonly Func<IImageProcessor> _imageProcessorFactory;
  56. private readonly Func<IDtoService> _dtoServiceFactory;
  57. /// <summary>
  58. /// Initializes a new instance of the <see cref="UserManager" /> class.
  59. /// </summary>
  60. /// <param name="logger">The logger.</param>
  61. /// <param name="configurationManager">The configuration manager.</param>
  62. /// <param name="userRepository">The user repository.</param>
  63. public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory)
  64. {
  65. _logger = logger;
  66. UserRepository = userRepository;
  67. _xmlSerializer = xmlSerializer;
  68. _networkManager = networkManager;
  69. _imageProcessorFactory = imageProcessorFactory;
  70. _dtoServiceFactory = dtoServiceFactory;
  71. ConfigurationManager = configurationManager;
  72. Users = new List<User>();
  73. }
  74. #region UserUpdated Event
  75. /// <summary>
  76. /// Occurs when [user updated].
  77. /// </summary>
  78. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  79. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  80. /// <summary>
  81. /// Called when [user updated].
  82. /// </summary>
  83. /// <param name="user">The user.</param>
  84. private void OnUserUpdated(User user)
  85. {
  86. EventHelper.FireEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  87. }
  88. #endregion
  89. #region UserDeleted Event
  90. /// <summary>
  91. /// Occurs when [user deleted].
  92. /// </summary>
  93. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  94. /// <summary>
  95. /// Called when [user deleted].
  96. /// </summary>
  97. /// <param name="user">The user.</param>
  98. private void OnUserDeleted(User user)
  99. {
  100. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  101. }
  102. #endregion
  103. /// <summary>
  104. /// Gets a User by Id
  105. /// </summary>
  106. /// <param name="id">The id.</param>
  107. /// <returns>User.</returns>
  108. /// <exception cref="System.ArgumentNullException"></exception>
  109. public User GetUserById(Guid id)
  110. {
  111. if (id == Guid.Empty)
  112. {
  113. throw new ArgumentNullException("id");
  114. }
  115. return Users.FirstOrDefault(u => u.Id == id);
  116. }
  117. public async Task Initialize()
  118. {
  119. Users = await LoadUsers().ConfigureAwait(false);
  120. }
  121. public async Task<bool> AuthenticateUser(string username, string password, string remoteEndPoint)
  122. {
  123. if (string.IsNullOrWhiteSpace(username))
  124. {
  125. throw new ArgumentNullException("username");
  126. }
  127. var user = Users.First(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  128. if (user.Configuration.IsDisabled)
  129. {
  130. throw new AuthenticationException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  131. }
  132. var success = string.Equals(GetPasswordHash(user), password.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  133. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  134. {
  135. success = string.Equals(GetLocalPasswordHash(user), password.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  136. }
  137. // Update LastActivityDate and LastLoginDate, then save
  138. if (success)
  139. {
  140. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  141. await UpdateUser(user).ConfigureAwait(false);
  142. }
  143. _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  144. return success;
  145. }
  146. private string GetPasswordHash(User user)
  147. {
  148. return string.IsNullOrEmpty(user.Password)
  149. ? GetSha1String(string.Empty)
  150. : user.Password;
  151. }
  152. private string GetLocalPasswordHash(User user)
  153. {
  154. return string.IsNullOrEmpty(user.LocalPassword)
  155. ? GetSha1String(string.Empty)
  156. : user.LocalPassword;
  157. }
  158. private bool IsPasswordEmpty(string passwordHash)
  159. {
  160. return string.Equals(passwordHash, GetSha1String(string.Empty), StringComparison.OrdinalIgnoreCase);
  161. }
  162. /// <summary>
  163. /// Gets the sha1 string.
  164. /// </summary>
  165. /// <param name="str">The STR.</param>
  166. /// <returns>System.String.</returns>
  167. private static string GetSha1String(string str)
  168. {
  169. using (var provider = SHA1.Create())
  170. {
  171. var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
  172. return BitConverter.ToString(hash).Replace("-", string.Empty);
  173. }
  174. }
  175. /// <summary>
  176. /// Loads the users from the repository
  177. /// </summary>
  178. /// <returns>IEnumerable{User}.</returns>
  179. private async Task<IEnumerable<User>> LoadUsers()
  180. {
  181. var users = UserRepository.RetrieveAllUsers().ToList();
  182. // There always has to be at least one user.
  183. if (users.Count == 0)
  184. {
  185. var name = Environment.UserName;
  186. var user = InstantiateNewUser(name);
  187. user.DateLastSaved = DateTime.UtcNow;
  188. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  189. users.Add(user);
  190. }
  191. return users;
  192. }
  193. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  194. {
  195. if (user == null)
  196. {
  197. throw new ArgumentNullException("user");
  198. }
  199. var passwordHash = GetPasswordHash(user);
  200. var hasConfiguredDefaultPassword = !IsPasswordEmpty(passwordHash);
  201. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  202. !IsPasswordEmpty(GetLocalPasswordHash(user)) :
  203. hasConfiguredDefaultPassword;
  204. var dto = new UserDto
  205. {
  206. Id = user.Id.ToString("N"),
  207. Name = user.Name,
  208. HasPassword = hasPassword,
  209. HasConfiguredPassword = hasConfiguredDefaultPassword,
  210. LastActivityDate = user.LastActivityDate,
  211. LastLoginDate = user.LastLoginDate,
  212. Configuration = user.Configuration
  213. };
  214. var image = user.GetImageInfo(ImageType.Primary, 0);
  215. if (image != null)
  216. {
  217. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  218. try
  219. {
  220. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  221. }
  222. catch (Exception ex)
  223. {
  224. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  225. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  226. }
  227. }
  228. return dto;
  229. }
  230. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  231. {
  232. try
  233. {
  234. return _imageProcessorFactory().GetImageCacheTag(item, image);
  235. }
  236. catch (Exception ex)
  237. {
  238. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  239. return null;
  240. }
  241. }
  242. /// <summary>
  243. /// Refreshes metadata for each user
  244. /// </summary>
  245. /// <param name="cancellationToken">The cancellation token.</param>
  246. /// <returns>Task.</returns>
  247. public Task RefreshUsersMetadata(CancellationToken cancellationToken)
  248. {
  249. var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(), cancellationToken)).ToList();
  250. return Task.WhenAll(tasks);
  251. }
  252. /// <summary>
  253. /// Renames the user.
  254. /// </summary>
  255. /// <param name="user">The user.</param>
  256. /// <param name="newName">The new name.</param>
  257. /// <returns>Task.</returns>
  258. /// <exception cref="System.ArgumentNullException">user</exception>
  259. /// <exception cref="System.ArgumentException"></exception>
  260. public async Task RenameUser(User user, string newName)
  261. {
  262. if (user == null)
  263. {
  264. throw new ArgumentNullException("user");
  265. }
  266. if (string.IsNullOrEmpty(newName))
  267. {
  268. throw new ArgumentNullException("newName");
  269. }
  270. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  271. {
  272. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  273. }
  274. if (user.Name.Equals(newName, StringComparison.Ordinal))
  275. {
  276. throw new ArgumentException("The new and old names must be different.");
  277. }
  278. await user.Rename(newName);
  279. OnUserUpdated(user);
  280. }
  281. /// <summary>
  282. /// Updates the user.
  283. /// </summary>
  284. /// <param name="user">The user.</param>
  285. /// <exception cref="System.ArgumentNullException">user</exception>
  286. /// <exception cref="System.ArgumentException"></exception>
  287. public async Task UpdateUser(User user)
  288. {
  289. if (user == null)
  290. {
  291. throw new ArgumentNullException("user");
  292. }
  293. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  294. {
  295. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  296. }
  297. user.DateModified = DateTime.UtcNow;
  298. user.DateLastSaved = DateTime.UtcNow;
  299. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  300. OnUserUpdated(user);
  301. }
  302. public event EventHandler<GenericEventArgs<User>> UserCreated;
  303. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  304. /// <summary>
  305. /// Creates the user.
  306. /// </summary>
  307. /// <param name="name">The name.</param>
  308. /// <returns>User.</returns>
  309. /// <exception cref="System.ArgumentNullException">name</exception>
  310. /// <exception cref="System.ArgumentException"></exception>
  311. public async Task<User> CreateUser(string name)
  312. {
  313. if (string.IsNullOrWhiteSpace(name))
  314. {
  315. throw new ArgumentNullException("name");
  316. }
  317. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  318. {
  319. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  320. }
  321. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  322. try
  323. {
  324. var user = InstantiateNewUser(name);
  325. var list = Users.ToList();
  326. list.Add(user);
  327. Users = list;
  328. user.DateLastSaved = DateTime.UtcNow;
  329. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  330. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  331. return user;
  332. }
  333. finally
  334. {
  335. _userListLock.Release();
  336. }
  337. }
  338. /// <summary>
  339. /// Deletes the user.
  340. /// </summary>
  341. /// <param name="user">The user.</param>
  342. /// <returns>Task.</returns>
  343. /// <exception cref="System.ArgumentNullException">user</exception>
  344. /// <exception cref="System.ArgumentException"></exception>
  345. public async Task DeleteUser(User user)
  346. {
  347. if (user == null)
  348. {
  349. throw new ArgumentNullException("user");
  350. }
  351. var allUsers = Users.ToList();
  352. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  353. {
  354. 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));
  355. }
  356. if (allUsers.Count == 1)
  357. {
  358. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  359. }
  360. if (user.Configuration.IsAdministrator && allUsers.Count(i => i.Configuration.IsAdministrator) == 1)
  361. {
  362. 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));
  363. }
  364. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  365. try
  366. {
  367. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  368. var path = user.ConfigurationFilePath;
  369. try
  370. {
  371. File.Delete(path);
  372. }
  373. catch (IOException ex)
  374. {
  375. _logger.ErrorException("Error deleting file {0}", ex, path);
  376. }
  377. // Force this to be lazy loaded again
  378. Users = await LoadUsers().ConfigureAwait(false);
  379. OnUserDeleted(user);
  380. }
  381. finally
  382. {
  383. _userListLock.Release();
  384. }
  385. }
  386. /// <summary>
  387. /// Resets the password by clearing it.
  388. /// </summary>
  389. /// <returns>Task.</returns>
  390. public Task ResetPassword(User user)
  391. {
  392. return ChangePassword(user, string.Empty);
  393. }
  394. /// <summary>
  395. /// Changes the password.
  396. /// </summary>
  397. /// <param name="user">The user.</param>
  398. /// <param name="newPassword">The new password.</param>
  399. /// <returns>Task.</returns>
  400. public async Task ChangePassword(User user, string newPassword)
  401. {
  402. if (user == null)
  403. {
  404. throw new ArgumentNullException("user");
  405. }
  406. user.Password = string.IsNullOrEmpty(newPassword) ? GetSha1String(string.Empty) : GetSha1String(newPassword);
  407. await UpdateUser(user).ConfigureAwait(false);
  408. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  409. }
  410. /// <summary>
  411. /// Instantiates the new user.
  412. /// </summary>
  413. /// <param name="name">The name.</param>
  414. /// <returns>User.</returns>
  415. private User InstantiateNewUser(string name)
  416. {
  417. return new User
  418. {
  419. Name = name,
  420. Id = ("MBUser" + name).GetMD5(),
  421. DateCreated = DateTime.UtcNow,
  422. DateModified = DateTime.UtcNow
  423. };
  424. }
  425. public void UpdateConfiguration(User user, UserConfiguration newConfiguration)
  426. {
  427. var xmlPath = user.ConfigurationFilePath;
  428. Directory.CreateDirectory(Path.GetDirectoryName(xmlPath));
  429. _xmlSerializer.SerializeToFile(newConfiguration, xmlPath);
  430. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  431. }
  432. }
  433. }