SqliteUserRepository.cs 7.7 KB

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