SqliteUserRepository.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 = GetConnection())
  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 (var connection = GetConnection())
  80. {
  81. connection.RunInTransaction(db =>
  82. {
  83. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  84. {
  85. statement.TryBind("@InternalId", user.InternalId);
  86. statement.TryBind("@data", serialized);
  87. statement.MoveNext();
  88. }
  89. }, TransactionMode);
  90. }
  91. }
  92. }
  93. /// <summary>
  94. /// Save a user in the repo
  95. /// </summary>
  96. public void CreateUser(User user)
  97. {
  98. if (user == null)
  99. {
  100. throw new ArgumentNullException(nameof(user));
  101. }
  102. var serialized = _jsonSerializer.SerializeToBytes(user);
  103. using (var connection = GetConnection())
  104. {
  105. connection.RunInTransaction(db =>
  106. {
  107. using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)"))
  108. {
  109. statement.TryBind("@guid", user.Id.ToGuidBlob());
  110. statement.TryBind("@data", serialized);
  111. statement.MoveNext();
  112. }
  113. var createdUser = GetUser(user.Id, connection);
  114. if (createdUser == null)
  115. {
  116. throw new ApplicationException("created user should never be null");
  117. }
  118. user.InternalId = createdUser.InternalId;
  119. }, TransactionMode);
  120. }
  121. }
  122. public void UpdateUser(User user)
  123. {
  124. if (user == null)
  125. {
  126. throw new ArgumentNullException(nameof(user));
  127. }
  128. var serialized = _jsonSerializer.SerializeToBytes(user);
  129. using (var connection = GetConnection())
  130. {
  131. connection.RunInTransaction(db =>
  132. {
  133. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  134. {
  135. statement.TryBind("@InternalId", user.InternalId);
  136. statement.TryBind("@data", serialized);
  137. statement.MoveNext();
  138. }
  139. }, TransactionMode);
  140. }
  141. }
  142. private User GetUser(Guid guid, ManagedConnection connection)
  143. {
  144. using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
  145. {
  146. statement.TryBind("@guid", guid);
  147. foreach (var row in statement.ExecuteQuery())
  148. {
  149. return GetUser(row);
  150. }
  151. }
  152. return null;
  153. }
  154. private User GetUser(IReadOnlyList<IResultSetValue> row)
  155. {
  156. var id = row[0].ToInt64();
  157. var guid = row[1].ReadGuidFromBlob();
  158. using (var stream = new MemoryStream(row[2].ToBlob()))
  159. {
  160. stream.Position = 0;
  161. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  162. user.InternalId = id;
  163. user.Id = guid;
  164. return user;
  165. }
  166. }
  167. /// <summary>
  168. /// Retrieve all users from the database
  169. /// </summary>
  170. /// <returns>IEnumerable{User}.</returns>
  171. public List<User> RetrieveAllUsers()
  172. {
  173. var list = new List<User>();
  174. using (var connection = GetConnection(true))
  175. {
  176. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  177. {
  178. list.Add(GetUser(row));
  179. }
  180. }
  181. return list;
  182. }
  183. /// <summary>
  184. /// Deletes the user.
  185. /// </summary>
  186. /// <param name="user">The user.</param>
  187. /// <returns>Task.</returns>
  188. /// <exception cref="ArgumentNullException">user</exception>
  189. public void DeleteUser(User user)
  190. {
  191. if (user == null)
  192. {
  193. throw new ArgumentNullException(nameof(user));
  194. }
  195. using (var connection = GetConnection())
  196. {
  197. connection.RunInTransaction(db =>
  198. {
  199. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  200. {
  201. statement.TryBind("@id", user.InternalId);
  202. statement.MoveNext();
  203. }
  204. }, TransactionMode);
  205. }
  206. }
  207. }
  208. }