AuthenticationRepository.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Security;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Model.Querying;
  5. using MediaBrowser.Server.Implementations.Persistence;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Security
  14. {
  15. public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository
  16. {
  17. private IDbConnection _connection;
  18. private readonly IServerApplicationPaths _appPaths;
  19. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  20. private IDbCommand _saveInfoCommand;
  21. public AuthenticationRepository(ILogManager logManager, IServerApplicationPaths appPaths)
  22. : base(logManager)
  23. {
  24. _appPaths = appPaths;
  25. }
  26. public async Task Initialize(IDbConnector dbConnector)
  27. {
  28. var dbFile = Path.Combine(_appPaths.DataPath, "authentication.db");
  29. _connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
  30. string[] queries = {
  31. "create table if not exists AccessTokens (Id GUID PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT, AppName TEXT, AppVersion TEXT, DeviceName TEXT, UserId TEXT, IsActive BIT, DateCreated DATETIME NOT NULL, DateRevoked DATETIME)",
  32. "create index if not exists idx_AccessTokens on AccessTokens(Id)",
  33. //pragmas
  34. "pragma temp_store = memory",
  35. "pragma shrink_memory"
  36. };
  37. _connection.RunQueries(queries, Logger);
  38. _connection.AddColumn(Logger, "AccessTokens", "AppVersion", "TEXT");
  39. PrepareStatements();
  40. }
  41. private void PrepareStatements()
  42. {
  43. _saveInfoCommand = _connection.CreateCommand();
  44. _saveInfoCommand.CommandText = "replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (@Id, @AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @IsActive, @DateCreated, @DateRevoked)";
  45. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@Id");
  46. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@AccessToken");
  47. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DeviceId");
  48. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@AppName");
  49. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@AppVersion");
  50. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DeviceName");
  51. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@UserId");
  52. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@IsActive");
  53. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DateCreated");
  54. _saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DateRevoked");
  55. }
  56. public Task Create(AuthenticationInfo info, CancellationToken cancellationToken)
  57. {
  58. info.Id = Guid.NewGuid().ToString("N");
  59. return Update(info, cancellationToken);
  60. }
  61. public async Task Update(AuthenticationInfo info, CancellationToken cancellationToken)
  62. {
  63. if (info == null)
  64. {
  65. throw new ArgumentNullException("info");
  66. }
  67. cancellationToken.ThrowIfCancellationRequested();
  68. await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  69. IDbTransaction transaction = null;
  70. try
  71. {
  72. transaction = _connection.BeginTransaction();
  73. var index = 0;
  74. _saveInfoCommand.GetParameter(index++).Value = new Guid(info.Id);
  75. _saveInfoCommand.GetParameter(index++).Value = info.AccessToken;
  76. _saveInfoCommand.GetParameter(index++).Value = info.DeviceId;
  77. _saveInfoCommand.GetParameter(index++).Value = info.AppName;
  78. _saveInfoCommand.GetParameter(index++).Value = info.AppVersion;
  79. _saveInfoCommand.GetParameter(index++).Value = info.DeviceName;
  80. _saveInfoCommand.GetParameter(index++).Value = info.UserId;
  81. _saveInfoCommand.GetParameter(index++).Value = info.IsActive;
  82. _saveInfoCommand.GetParameter(index++).Value = info.DateCreated;
  83. _saveInfoCommand.GetParameter(index++).Value = info.DateRevoked;
  84. _saveInfoCommand.Transaction = transaction;
  85. _saveInfoCommand.ExecuteNonQuery();
  86. transaction.Commit();
  87. }
  88. catch (OperationCanceledException)
  89. {
  90. if (transaction != null)
  91. {
  92. transaction.Rollback();
  93. }
  94. throw;
  95. }
  96. catch (Exception e)
  97. {
  98. Logger.ErrorException("Failed to save record:", e);
  99. if (transaction != null)
  100. {
  101. transaction.Rollback();
  102. }
  103. throw;
  104. }
  105. finally
  106. {
  107. if (transaction != null)
  108. {
  109. transaction.Dispose();
  110. }
  111. WriteLock.Release();
  112. }
  113. }
  114. private const string BaseSelectText = "select Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked from AccessTokens";
  115. public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query)
  116. {
  117. if (query == null)
  118. {
  119. throw new ArgumentNullException("query");
  120. }
  121. using (var cmd = _connection.CreateCommand())
  122. {
  123. cmd.CommandText = BaseSelectText;
  124. var whereClauses = new List<string>();
  125. var startIndex = query.StartIndex ?? 0;
  126. if (!string.IsNullOrWhiteSpace(query.AccessToken))
  127. {
  128. whereClauses.Add("AccessToken=@AccessToken");
  129. cmd.Parameters.Add(cmd, "@AccessToken", DbType.String).Value = query.AccessToken;
  130. }
  131. if (!string.IsNullOrWhiteSpace(query.UserId))
  132. {
  133. whereClauses.Add("UserId=@UserId");
  134. cmd.Parameters.Add(cmd, "@UserId", DbType.String).Value = query.UserId;
  135. }
  136. if (!string.IsNullOrWhiteSpace(query.DeviceId))
  137. {
  138. whereClauses.Add("DeviceId=@DeviceId");
  139. cmd.Parameters.Add(cmd, "@DeviceId", DbType.String).Value = query.DeviceId;
  140. }
  141. if (query.IsActive.HasValue)
  142. {
  143. whereClauses.Add("IsActive=@IsActive");
  144. cmd.Parameters.Add(cmd, "@IsActive", DbType.Boolean).Value = query.IsActive.Value;
  145. }
  146. if (query.HasUser.HasValue)
  147. {
  148. if (query.HasUser.Value)
  149. {
  150. whereClauses.Add("UserId not null");
  151. }
  152. else
  153. {
  154. whereClauses.Add("UserId is null");
  155. }
  156. }
  157. var whereTextWithoutPaging = whereClauses.Count == 0 ?
  158. string.Empty :
  159. " where " + string.Join(" AND ", whereClauses.ToArray());
  160. if (startIndex > 0)
  161. {
  162. var pagingWhereText = whereClauses.Count == 0 ?
  163. string.Empty :
  164. " where " + string.Join(" AND ", whereClauses.ToArray());
  165. whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM AccessTokens {0} ORDER BY DateCreated LIMIT {1})",
  166. pagingWhereText,
  167. startIndex.ToString(_usCulture)));
  168. }
  169. var whereText = whereClauses.Count == 0 ?
  170. string.Empty :
  171. " where " + string.Join(" AND ", whereClauses.ToArray());
  172. cmd.CommandText += whereText;
  173. cmd.CommandText += " ORDER BY DateCreated";
  174. if (query.Limit.HasValue)
  175. {
  176. cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(_usCulture);
  177. }
  178. cmd.CommandText += "; select count (Id) from AccessTokens" + whereTextWithoutPaging;
  179. var list = new List<AuthenticationInfo>();
  180. var count = 0;
  181. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  182. {
  183. while (reader.Read())
  184. {
  185. list.Add(Get(reader));
  186. }
  187. if (reader.NextResult() && reader.Read())
  188. {
  189. count = reader.GetInt32(0);
  190. }
  191. }
  192. return new QueryResult<AuthenticationInfo>()
  193. {
  194. Items = list.ToArray(),
  195. TotalRecordCount = count
  196. };
  197. }
  198. }
  199. public AuthenticationInfo Get(string id)
  200. {
  201. if (string.IsNullOrEmpty(id))
  202. {
  203. throw new ArgumentNullException("id");
  204. }
  205. var guid = new Guid(id);
  206. using (var cmd = _connection.CreateCommand())
  207. {
  208. cmd.CommandText = BaseSelectText + " where Id=@Id";
  209. cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = guid;
  210. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  211. {
  212. if (reader.Read())
  213. {
  214. return Get(reader);
  215. }
  216. }
  217. }
  218. return null;
  219. }
  220. private AuthenticationInfo Get(IDataReader reader)
  221. {
  222. var info = new AuthenticationInfo
  223. {
  224. Id = reader.GetGuid(0).ToString("N"),
  225. AccessToken = reader.GetString(1)
  226. };
  227. if (!reader.IsDBNull(2))
  228. {
  229. info.DeviceId = reader.GetString(2);
  230. }
  231. if (!reader.IsDBNull(3))
  232. {
  233. info.AppName = reader.GetString(3);
  234. }
  235. if (!reader.IsDBNull(4))
  236. {
  237. info.AppVersion = reader.GetString(4);
  238. }
  239. if (!reader.IsDBNull(5))
  240. {
  241. info.DeviceName = reader.GetString(5);
  242. }
  243. if (!reader.IsDBNull(6))
  244. {
  245. info.UserId = reader.GetString(6);
  246. }
  247. info.IsActive = reader.GetBoolean(7);
  248. info.DateCreated = reader.GetDateTime(8).ToUniversalTime();
  249. if (!reader.IsDBNull(9))
  250. {
  251. info.DateRevoked = reader.GetDateTime(9).ToUniversalTime();
  252. }
  253. return info;
  254. }
  255. protected override void CloseConnection()
  256. {
  257. if (_connection != null)
  258. {
  259. if (_connection.IsOpen())
  260. {
  261. _connection.Close();
  262. }
  263. _connection.Dispose();
  264. _connection = null;
  265. }
  266. }
  267. }
  268. }