SqliteUserRepository.cs 7.9 KB

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