SqliteUserRepository.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. ILogger<SqliteUserRepository> logger,
  20. IServerApplicationPaths appPaths,
  21. IJsonSerializer jsonSerializer)
  22. : base(logger)
  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 = GetConnection())
  39. {
  40. var localUsersTableExists = TableExists(connection, "LocalUsersv2");
  41. connection.RunQueries(new[] {
  42. "create table if not exists LocalUsersv2 (Id INTEGER PRIMARY KEY, guid GUID NOT NULL, data BLOB NOT NULL)",
  43. "drop index if exists idx_users"
  44. });
  45. if (!localUsersTableExists && TableExists(connection, "Users"))
  46. {
  47. TryMigrateToLocalUsersTable(connection);
  48. }
  49. RemoveEmptyPasswordHashes(connection);
  50. }
  51. }
  52. private void TryMigrateToLocalUsersTable(ManagedConnection connection)
  53. {
  54. try
  55. {
  56. connection.RunQueries(new[]
  57. {
  58. "INSERT INTO LocalUsersv2 (guid, data) SELECT guid,data from users"
  59. });
  60. }
  61. catch (Exception ex)
  62. {
  63. Logger.LogError(ex, "Error migrating users database");
  64. }
  65. }
  66. private void RemoveEmptyPasswordHashes(ManagedConnection connection)
  67. {
  68. foreach (var user in RetrieveAllUsers(connection))
  69. {
  70. // If the user password is the sha1 hash of the empty string, remove it
  71. if (!string.Equals(user.Password, "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal)
  72. && !string.Equals(user.Password, "$SHA1$DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal))
  73. {
  74. continue;
  75. }
  76. user.Password = null;
  77. var serialized = _jsonSerializer.SerializeToBytes(user);
  78. connection.RunInTransaction(db =>
  79. {
  80. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  81. {
  82. statement.TryBind("@InternalId", user.InternalId);
  83. statement.TryBind("@data", serialized);
  84. statement.MoveNext();
  85. }
  86. }, TransactionMode);
  87. }
  88. }
  89. /// <summary>
  90. /// Save a user in the repo
  91. /// </summary>
  92. public void CreateUser(User user)
  93. {
  94. if (user == null)
  95. {
  96. throw new ArgumentNullException(nameof(user));
  97. }
  98. var serialized = _jsonSerializer.SerializeToBytes(user);
  99. using (var connection = GetConnection())
  100. {
  101. connection.RunInTransaction(db =>
  102. {
  103. using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)"))
  104. {
  105. statement.TryBind("@guid", user.Id.ToGuidBlob());
  106. statement.TryBind("@data", serialized);
  107. statement.MoveNext();
  108. }
  109. var createdUser = GetUser(user.Id, connection);
  110. if (createdUser == null)
  111. {
  112. throw new ApplicationException("created user should never be null");
  113. }
  114. user.InternalId = createdUser.InternalId;
  115. }, TransactionMode);
  116. }
  117. }
  118. public void UpdateUser(User user)
  119. {
  120. if (user == null)
  121. {
  122. throw new ArgumentNullException(nameof(user));
  123. }
  124. var serialized = _jsonSerializer.SerializeToBytes(user);
  125. using (var connection = GetConnection())
  126. {
  127. connection.RunInTransaction(db =>
  128. {
  129. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  130. {
  131. statement.TryBind("@InternalId", user.InternalId);
  132. statement.TryBind("@data", serialized);
  133. statement.MoveNext();
  134. }
  135. }, TransactionMode);
  136. }
  137. }
  138. private User GetUser(Guid guid, ManagedConnection connection)
  139. {
  140. using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
  141. {
  142. statement.TryBind("@guid", guid);
  143. foreach (var row in statement.ExecuteQuery())
  144. {
  145. return GetUser(row);
  146. }
  147. }
  148. return null;
  149. }
  150. private User GetUser(IReadOnlyList<IResultSetValue> row)
  151. {
  152. var id = row[0].ToInt64();
  153. var guid = row[1].ReadGuidFromBlob();
  154. using (var stream = new MemoryStream(row[2].ToBlob()))
  155. {
  156. stream.Position = 0;
  157. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  158. user.InternalId = id;
  159. user.Id = guid;
  160. return user;
  161. }
  162. }
  163. /// <summary>
  164. /// Retrieve all users from the database
  165. /// </summary>
  166. /// <returns>IEnumerable{User}.</returns>
  167. public List<User> RetrieveAllUsers()
  168. {
  169. using (var connection = GetConnection(true))
  170. {
  171. return new List<User>(RetrieveAllUsers(connection));
  172. }
  173. }
  174. /// <summary>
  175. /// Retrieve all users from the database
  176. /// </summary>
  177. /// <returns>IEnumerable{User}.</returns>
  178. private IEnumerable<User> RetrieveAllUsers(ManagedConnection connection)
  179. {
  180. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  181. {
  182. yield return GetUser(row);
  183. }
  184. }
  185. /// <summary>
  186. /// Deletes the user.
  187. /// </summary>
  188. /// <param name="user">The user.</param>
  189. /// <returns>Task.</returns>
  190. /// <exception cref="ArgumentNullException">user</exception>
  191. public void DeleteUser(User user)
  192. {
  193. if (user == null)
  194. {
  195. throw new ArgumentNullException(nameof(user));
  196. }
  197. using (var connection = GetConnection())
  198. {
  199. connection.RunInTransaction(db =>
  200. {
  201. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  202. {
  203. statement.TryBind("@id", user.InternalId);
  204. statement.MoveNext();
  205. }
  206. }, TransactionMode);
  207. }
  208. }
  209. }
  210. }