2
0

SqliteUserRepository.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text.Json;
  7. using MediaBrowser.Common.Json;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Persistence;
  11. using Microsoft.Extensions.Logging;
  12. using SQLitePCL.pretty;
  13. namespace Emby.Server.Implementations.Data
  14. {
  15. /// <summary>
  16. /// Class SQLiteUserRepository
  17. /// </summary>
  18. public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
  19. {
  20. private readonly JsonSerializerOptions _jsonOptions;
  21. public SqliteUserRepository(
  22. ILogger<SqliteUserRepository> logger,
  23. IServerApplicationPaths appPaths)
  24. : base(logger)
  25. {
  26. _jsonOptions = JsonDefaults.GetOptions();;
  27. DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
  28. }
  29. /// <summary>
  30. /// Gets the name of the repository
  31. /// </summary>
  32. /// <value>The name.</value>
  33. public string Name => "SQLite";
  34. /// <summary>
  35. /// Opens the connection to the database.
  36. /// </summary>
  37. public void Initialize()
  38. {
  39. using (var connection = GetConnection())
  40. {
  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(connection);
  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(ManagedConnection connection)
  68. {
  69. foreach (var user in RetrieveAllUsers(connection))
  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.SerializeToUtf8Bytes(user, _jsonOptions);
  79. connection.RunInTransaction(db =>
  80. {
  81. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  82. {
  83. statement.TryBind("@InternalId", user.InternalId);
  84. statement.TryBind("@data", serialized);
  85. statement.MoveNext();
  86. }
  87. }, TransactionMode);
  88. }
  89. }
  90. /// <summary>
  91. /// Save a user in the repo
  92. /// </summary>
  93. public void CreateUser(User user)
  94. {
  95. if (user == null)
  96. {
  97. throw new ArgumentNullException(nameof(user));
  98. }
  99. var serialized = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions);
  100. using (var connection = GetConnection())
  101. {
  102. connection.RunInTransaction(db =>
  103. {
  104. using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)"))
  105. {
  106. statement.TryBind("@guid", user.Id.ToByteArray());
  107. statement.TryBind("@data", serialized);
  108. statement.MoveNext();
  109. }
  110. var createdUser = GetUser(user.Id, connection);
  111. if (createdUser == null)
  112. {
  113. throw new ApplicationException("created user should never be null");
  114. }
  115. user.InternalId = createdUser.InternalId;
  116. }, TransactionMode);
  117. }
  118. }
  119. public void UpdateUser(User user)
  120. {
  121. if (user == null)
  122. {
  123. throw new ArgumentNullException(nameof(user));
  124. }
  125. var serialized = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions);
  126. using (var connection = GetConnection())
  127. {
  128. connection.RunInTransaction(db =>
  129. {
  130. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  131. {
  132. statement.TryBind("@InternalId", user.InternalId);
  133. statement.TryBind("@data", serialized);
  134. statement.MoveNext();
  135. }
  136. }, TransactionMode);
  137. }
  138. }
  139. private User GetUser(Guid guid, ManagedConnection connection)
  140. {
  141. using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
  142. {
  143. statement.TryBind("@guid", guid);
  144. foreach (var row in statement.ExecuteQuery())
  145. {
  146. return GetUser(row);
  147. }
  148. }
  149. return null;
  150. }
  151. private User GetUser(IReadOnlyList<IResultSetValue> row)
  152. {
  153. var id = row[0].ToInt64();
  154. var guid = row[1].ReadGuidFromBlob();
  155. var user = JsonSerializer.Deserialize<User>(row[2].ToBlob(), _jsonOptions);
  156. user.InternalId = id;
  157. user.Id = guid;
  158. return user;
  159. }
  160. /// <summary>
  161. /// Retrieve all users from the database
  162. /// </summary>
  163. /// <returns>IEnumerable{User}.</returns>
  164. public List<User> RetrieveAllUsers()
  165. {
  166. using (var connection = GetConnection(true))
  167. {
  168. return new List<User>(RetrieveAllUsers(connection));
  169. }
  170. }
  171. /// <summary>
  172. /// Retrieve all users from the database
  173. /// </summary>
  174. /// <returns>IEnumerable{User}.</returns>
  175. private IEnumerable<User> RetrieveAllUsers(ManagedConnection connection)
  176. {
  177. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  178. {
  179. yield return GetUser(row);
  180. }
  181. }
  182. /// <summary>
  183. /// Deletes the user.
  184. /// </summary>
  185. /// <param name="user">The user.</param>
  186. /// <returns>Task.</returns>
  187. /// <exception cref="ArgumentNullException">user</exception>
  188. public void DeleteUser(User user)
  189. {
  190. if (user == null)
  191. {
  192. throw new ArgumentNullException(nameof(user));
  193. }
  194. using (var connection = GetConnection())
  195. {
  196. connection.RunInTransaction(db =>
  197. {
  198. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  199. {
  200. statement.TryBind("@id", user.InternalId);
  201. statement.MoveNext();
  202. }
  203. }, TransactionMode);
  204. }
  205. }
  206. }
  207. }