SqliteUserRepository.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 = CreateConnection())
  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") || !string.Equals(user.Password, "$SHA1$DA39A3EE5E6B4B0D3255BFEF95601890AFD80709"))
  73. {
  74. continue;
  75. }
  76. user.Password = null;
  77. var serialized = _jsonSerializer.SerializeToBytes(user);
  78. using (WriteLock.Write())
  79. using (var connection = CreateConnection())
  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 (WriteLock.Write())
  104. {
  105. using (var connection = CreateConnection())
  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, false);
  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. }
  125. public void UpdateUser(User user)
  126. {
  127. if (user == null)
  128. {
  129. throw new ArgumentNullException(nameof(user));
  130. }
  131. var serialized = _jsonSerializer.SerializeToBytes(user);
  132. using (WriteLock.Write())
  133. {
  134. using (var connection = CreateConnection())
  135. {
  136. connection.RunInTransaction(db =>
  137. {
  138. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  139. {
  140. statement.TryBind("@InternalId", user.InternalId);
  141. statement.TryBind("@data", serialized);
  142. statement.MoveNext();
  143. }
  144. }, TransactionMode);
  145. }
  146. }
  147. }
  148. private User GetUser(Guid guid, bool openLock)
  149. {
  150. using (openLock ? WriteLock.Read() : null)
  151. {
  152. using (var connection = CreateConnection(true))
  153. {
  154. using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
  155. {
  156. statement.TryBind("@guid", guid);
  157. foreach (var row in statement.ExecuteQuery())
  158. {
  159. return GetUser(row);
  160. }
  161. }
  162. }
  163. }
  164. return null;
  165. }
  166. private User GetUser(IReadOnlyList<IResultSetValue> row)
  167. {
  168. var id = row[0].ToInt64();
  169. var guid = row[1].ReadGuidFromBlob();
  170. using (var stream = new MemoryStream(row[2].ToBlob()))
  171. {
  172. stream.Position = 0;
  173. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  174. user.InternalId = id;
  175. user.Id = guid;
  176. return user;
  177. }
  178. }
  179. /// <summary>
  180. /// Retrieve all users from the database
  181. /// </summary>
  182. /// <returns>IEnumerable{User}.</returns>
  183. public List<User> RetrieveAllUsers()
  184. {
  185. var list = new List<User>();
  186. using (WriteLock.Read())
  187. {
  188. using (var connection = CreateConnection(true))
  189. {
  190. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  191. {
  192. list.Add(GetUser(row));
  193. }
  194. }
  195. }
  196. return list;
  197. }
  198. /// <summary>
  199. /// Deletes the user.
  200. /// </summary>
  201. /// <param name="user">The user.</param>
  202. /// <returns>Task.</returns>
  203. /// <exception cref="ArgumentNullException">user</exception>
  204. public void DeleteUser(User user)
  205. {
  206. if (user == null)
  207. {
  208. throw new ArgumentNullException(nameof(user));
  209. }
  210. using (WriteLock.Write())
  211. {
  212. using (var connection = CreateConnection())
  213. {
  214. connection.RunInTransaction(db =>
  215. {
  216. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  217. {
  218. statement.TryBind("@id", user.InternalId);
  219. statement.MoveNext();
  220. }
  221. }, TransactionMode);
  222. }
  223. }
  224. }
  225. }
  226. }