SqliteUserRepository.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text.Json;
  6. using MediaBrowser.Common.Json;
  7. using MediaBrowser.Controller;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Persistence;
  10. using Microsoft.Extensions.Logging;
  11. using SQLitePCL.pretty;
  12. namespace Emby.Server.Implementations.Data
  13. {
  14. /// <summary>
  15. /// Class SQLiteUserRepository
  16. /// </summary>
  17. public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
  18. {
  19. private readonly JsonSerializerOptions _jsonOptions;
  20. public SqliteUserRepository(
  21. ILogger<SqliteUserRepository> logger,
  22. IServerApplicationPaths appPaths)
  23. : base(logger)
  24. {
  25. _jsonOptions = JsonDefaults.GetOptions();
  26. DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
  27. }
  28. /// <summary>
  29. /// Gets the name of the repository
  30. /// </summary>
  31. /// <value>The name.</value>
  32. public string Name => "SQLite";
  33. /// <summary>
  34. /// Opens the connection to the database.
  35. /// </summary>
  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.SerializeToUtf8Bytes(user, _jsonOptions);
  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.SerializeToUtf8Bytes(user, _jsonOptions);
  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.ToByteArray());
  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.SerializeToUtf8Bytes(user, _jsonOptions);
  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. var user = JsonSerializer.Deserialize<User>(row[2].ToBlob(), _jsonOptions);
  155. user.InternalId = id;
  156. user.Id = guid;
  157. return user;
  158. }
  159. /// <summary>
  160. /// Retrieve all users from the database
  161. /// </summary>
  162. /// <returns>IEnumerable{User}.</returns>
  163. public List<User> RetrieveAllUsers()
  164. {
  165. using (var connection = GetConnection(true))
  166. {
  167. return new List<User>(RetrieveAllUsers(connection));
  168. }
  169. }
  170. /// <summary>
  171. /// Retrieve all users from the database
  172. /// </summary>
  173. /// <returns>IEnumerable{User}.</returns>
  174. private IEnumerable<User> RetrieveAllUsers(ManagedConnection connection)
  175. {
  176. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  177. {
  178. yield return GetUser(row);
  179. }
  180. }
  181. /// <summary>
  182. /// Deletes the user.
  183. /// </summary>
  184. /// <param name="user">The user.</param>
  185. /// <returns>Task.</returns>
  186. /// <exception cref="ArgumentNullException">user</exception>
  187. public void DeleteUser(User user)
  188. {
  189. if (user == null)
  190. {
  191. throw new ArgumentNullException(nameof(user));
  192. }
  193. using (var connection = GetConnection())
  194. {
  195. connection.RunInTransaction(db =>
  196. {
  197. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  198. {
  199. statement.TryBind("@id", user.InternalId);
  200. statement.MoveNext();
  201. }
  202. }, TransactionMode);
  203. }
  204. }
  205. }
  206. }