1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Emby.Server.Implementations.Data;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
using SQLitePCL.pretty;
using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.Security
{
public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository
{
private readonly IServerApplicationPaths _appPaths;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
public AuthenticationRepository(ILogger logger, IServerApplicationPaths appPaths)
: base(logger)
{
_appPaths = appPaths;
DbFilePath = Path.Combine(appPaths.DataPath, "authentication.db");
}
public void Initialize()
{
using (var connection = CreateConnection())
{
RunDefaultInitialization(connection);
string[] queries = {
"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)",
"create index if not exists idx_AccessTokens on AccessTokens(Id)"
};
connection.RunQueries(queries);
connection.RunInTransaction(db =>
{
var existingColumnNames = GetColumnNames(db, "AccessTokens");
AddColumn(db, "AccessTokens", "AppVersion", "TEXT", existingColumnNames);
}, TransactionMode);
}
}
public void Create(AuthenticationInfo info, CancellationToken cancellationToken)
{
info.Id = Guid.NewGuid().ToString("N");
Update(info, cancellationToken);
}
public void Update(AuthenticationInfo info, CancellationToken cancellationToken)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
connection.RunInTransaction(db =>
{
using (var statement = db.PrepareStatement("replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (@Id, @AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @IsActive, @DateCreated, @DateRevoked)"))
{
statement.TryBind("@Id", info.Id.ToGuidBlob());
statement.TryBind("@AccessToken", info.AccessToken);
statement.TryBind("@DeviceId", info.DeviceId);
statement.TryBind("@AppName", info.AppName);
statement.TryBind("@AppVersion", info.AppVersion);
statement.TryBind("@DeviceName", info.DeviceName);
statement.TryBind("@UserId", info.UserId);
statement.TryBind("@IsActive", info.IsActive);
statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue());
if (info.DateRevoked.HasValue)
{
statement.TryBind("@DateRevoked", info.DateRevoked.Value.ToDateTimeParamValue());
}
else
{
statement.TryBindNull("@DateRevoked");
}
statement.MoveNext();
}
}, TransactionMode);
}
}
}
private const string BaseSelectText = "select Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked from AccessTokens";
private void BindAuthenticationQueryParams(AuthenticationInfoQuery query, IStatement statement)
{
if (!string.IsNullOrWhiteSpace(query.AccessToken))
{
statement.TryBind("@AccessToken", query.AccessToken);
}
if (!string.IsNullOrWhiteSpace(query.UserId))
{
statement.TryBind("@UserId", query.UserId);
}
if (!string.IsNullOrWhiteSpace(query.DeviceId))
{
statement.TryBind("@DeviceId", query.DeviceId);
}
if (query.IsActive.HasValue)
{
statement.TryBind("@IsActive", query.IsActive.Value);
}
}
public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var commandText = BaseSelectText;
var whereClauses = new List<string>();
var startIndex = query.StartIndex ?? 0;
if (!string.IsNullOrWhiteSpace(query.AccessToken))
{
whereClauses.Add("AccessToken=@AccessToken");
}
if (!string.IsNullOrWhiteSpace(query.UserId))
{
whereClauses.Add("UserId=@UserId");
}
if (!string.IsNullOrWhiteSpace(query.DeviceId))
{
whereClauses.Add("DeviceId=@DeviceId");
}
if (query.IsActive.HasValue)
{
whereClauses.Add("IsActive=@IsActive");
}
if (query.HasUser.HasValue)
{
if (query.HasUser.Value)
{
whereClauses.Add("UserId not null");
}
else
{
whereClauses.Add("UserId is null");
}
}
var whereTextWithoutPaging = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count));
if (startIndex > 0)
{
var pagingWhereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count));
whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM AccessTokens {0} ORDER BY DateCreated LIMIT {1})",
pagingWhereText,
startIndex.ToString(_usCulture)));
}
var whereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count));
commandText += whereText;
commandText += " ORDER BY DateCreated";
if (query.Limit.HasValue)
{
commandText += " LIMIT " + query.Limit.Value.ToString(_usCulture);
}
var list = new List<AuthenticationInfo>();
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
return connection.RunInTransaction(db =>
{
var result = new QueryResult<AuthenticationInfo>();
var statementTexts = new List<string>();
statementTexts.Add(commandText);
statementTexts.Add("select count (Id) from AccessTokens" + whereTextWithoutPaging);
var statements = PrepareAllSafe(db, statementTexts)
.ToList();
using (var statement = statements[0])
{
BindAuthenticationQueryParams(query, statement);
foreach (var row in statement.ExecuteQuery())
{
list.Add(Get(row));
}
using (var totalCountStatement = statements[1])
{
BindAuthenticationQueryParams(query, totalCountStatement);
result.TotalRecordCount = totalCountStatement.ExecuteQuery()
.SelectScalarInt()
.First();
}
}
result.Items = list.ToArray(list.Count);
return result;
}, ReadTransactionMode);
}
}
}
public AuthenticationInfo Get(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
var commandText = BaseSelectText + " where Id=@Id";
using (var statement = connection.PrepareStatement(commandText))
{
statement.BindParameters["@Id"].Bind(id.ToGuidBlob());
foreach (var row in statement.ExecuteQuery())
{
return Get(row);
}
return null;
}
}
}
}
private AuthenticationInfo Get(IReadOnlyList<IResultSetValue> reader)
{
var info = new AuthenticationInfo
{
Id = reader[0].ReadGuidFromBlob().ToString("N"),
AccessToken = reader[1].ToString()
};
if (reader[2].SQLiteType != SQLiteType.Null)
{
info.DeviceId = reader[2].ToString();
}
if (reader[3].SQLiteType != SQLiteType.Null)
{
info.AppName = reader[3].ToString();
}
if (reader[4].SQLiteType != SQLiteType.Null)
{
info.AppVersion = reader[4].ToString();
}
if (reader[5].SQLiteType != SQLiteType.Null)
{
info.DeviceName = reader[5].ToString();
}
if (reader[6].SQLiteType != SQLiteType.Null)
{
info.UserId = reader[6].ToString();
}
info.IsActive = reader[7].ToBool();
info.DateCreated = reader[8].ReadDateTime();
if (reader[9].SQLiteType != SQLiteType.Null)
{
info.DateRevoked = reader[9].ReadDateTime();
}
return info;
}
}
}
|