SqliteUserRepository.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Serialization;
  8. using Microsoft.Extensions.Logging;
  9. using SQLitePCL.pretty;
  10. namespace Emby.Server.Implementations.Data
  11. {
  12. /// <summary>
  13. /// Class SQLiteUserRepository
  14. /// </summary>
  15. public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
  16. {
  17. private readonly IJsonSerializer _jsonSerializer;
  18. public SqliteUserRepository(
  19. ILoggerFactory loggerFactory,
  20. IServerApplicationPaths appPaths,
  21. IJsonSerializer jsonSerializer)
  22. : base(loggerFactory.CreateLogger(nameof(SqliteUserRepository)))
  23. {
  24. _jsonSerializer = jsonSerializer;
  25. DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
  26. }
  27. /// <summary>
  28. /// Gets the name of the repository
  29. /// </summary>
  30. /// <value>The name.</value>
  31. public string Name => "SQLite";
  32. /// <summary>
  33. /// Opens the connection to the database
  34. /// </summary>
  35. /// <returns>Task.</returns>
  36. public void Initialize()
  37. {
  38. using (var connection = CreateConnection())
  39. {
  40. RunDefaultInitialization(connection);
  41. var localUsersTableExists = TableExists(connection, "LocalUsersv2");
  42. connection.RunQueries(new[] {
  43. "create table if not exists LocalUsersv2 (Id INTEGER PRIMARY KEY, guid GUID NOT NULL, data BLOB NOT NULL)",
  44. "drop index if exists idx_users"
  45. });
  46. if (!localUsersTableExists && TableExists(connection, "Users"))
  47. {
  48. TryMigrateToLocalUsersTable(connection);
  49. }
  50. RemoveEmptyPasswordHashes();
  51. }
  52. }
  53. private void TryMigrateToLocalUsersTable(ManagedConnection connection)
  54. {
  55. try
  56. {
  57. connection.RunQueries(new[]
  58. {
  59. "INSERT INTO LocalUsersv2 (guid, data) SELECT guid,data from users"
  60. });
  61. }
  62. catch (Exception ex)
  63. {
  64. Logger.LogError(ex, "Error migrating users database");
  65. }
  66. }
  67. private void RemoveEmptyPasswordHashes()
  68. {
  69. foreach (var user in RetrieveAllUsers())
  70. {
  71. // If the user password is the sha1 hash of the empty string, remove it
  72. if (!string.Equals(user.Password, "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal)
  73. && !string.Equals(user.Password, "$SHA1$DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal))
  74. {
  75. continue;
  76. }
  77. user.Password = null;
  78. var serialized = _jsonSerializer.SerializeToBytes(user);
  79. using (WriteLock.Write())
  80. using (var connection = CreateConnection())
  81. {
  82. connection.RunInTransaction(db =>
  83. {
  84. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  85. {
  86. statement.TryBind("@InternalId", user.InternalId);
  87. statement.TryBind("@data", serialized);
  88. statement.MoveNext();
  89. }
  90. }, TransactionMode);
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// Save a user in the repo
  96. /// </summary>
  97. public void CreateUser(User user)
  98. {
  99. if (user == null)
  100. {
  101. throw new ArgumentNullException(nameof(user));
  102. }
  103. var serialized = _jsonSerializer.SerializeToBytes(user);
  104. using (WriteLock.Write())
  105. {
  106. using (var connection = CreateConnection())
  107. {
  108. connection.RunInTransaction(db =>
  109. {
  110. using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)"))
  111. {
  112. statement.TryBind("@guid", user.Id.ToGuidBlob());
  113. statement.TryBind("@data", serialized);
  114. statement.MoveNext();
  115. }
  116. var createdUser = GetUser(user.Id, false);
  117. if (createdUser == null)
  118. {
  119. throw new ApplicationException("created user should never be null");
  120. }
  121. user.InternalId = createdUser.InternalId;
  122. }, TransactionMode);
  123. }
  124. }
  125. }
  126. public void UpdateUser(User user)
  127. {
  128. if (user == null)
  129. {
  130. throw new ArgumentNullException(nameof(user));
  131. }
  132. var serialized = _jsonSerializer.SerializeToBytes(user);
  133. using (WriteLock.Write())
  134. {
  135. using (var connection = CreateConnection())
  136. {
  137. connection.RunInTransaction(db =>
  138. {
  139. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  140. {
  141. statement.TryBind("@InternalId", user.InternalId);
  142. statement.TryBind("@data", serialized);
  143. statement.MoveNext();
  144. }
  145. }, TransactionMode);
  146. }
  147. }
  148. }
  149. private User GetUser(Guid guid, bool openLock)
  150. {
  151. using (openLock ? WriteLock.Read() : null)
  152. {
  153. using (var connection = CreateConnection(true))
  154. {
  155. using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
  156. {
  157. statement.TryBind("@guid", guid);
  158. foreach (var row in statement.ExecuteQuery())
  159. {
  160. return GetUser(row);
  161. }
  162. }
  163. }
  164. }
  165. return null;
  166. }
  167. private User GetUser(IReadOnlyList<IResultSetValue> row)
  168. {
  169. var id = row[0].ToInt64();
  170. var guid = row[1].ReadGuidFromBlob();
  171. using (var stream = new MemoryStream(row[2].ToBlob()))
  172. {
  173. stream.Position = 0;
  174. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  175. user.InternalId = id;
  176. user.Id = guid;
  177. return user;
  178. }
  179. }
  180. /// <summary>
  181. /// Retrieve all users from the database
  182. /// </summary>
  183. /// <returns>IEnumerable{User}.</returns>
  184. public List<User> RetrieveAllUsers()
  185. {
  186. var list = new List<User>();
  187. using (WriteLock.Read())
  188. {
  189. using (var connection = CreateConnection(true))
  190. {
  191. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  192. {
  193. list.Add(GetUser(row));
  194. }
  195. }
  196. }
  197. return list;
  198. }
  199. /// <summary>
  200. /// Deletes the user.
  201. /// </summary>
  202. /// <param name="user">The user.</param>
  203. /// <returns>Task.</returns>
  204. /// <exception cref="ArgumentNullException">user</exception>
  205. public void DeleteUser(User user)
  206. {
  207. if (user == null)
  208. {
  209. throw new ArgumentNullException(nameof(user));
  210. }
  211. using (WriteLock.Write())
  212. {
  213. using (var connection = CreateConnection())
  214. {
  215. connection.RunInTransaction(db =>
  216. {
  217. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  218. {
  219. statement.TryBind("@id", user.InternalId);
  220. statement.MoveNext();
  221. }
  222. }, TransactionMode);
  223. }
  224. }
  225. }
  226. }
  227. }