jellyfin/MediaBrowser.Server.Implementations/Security/AuthenticationRepository.cs

318 lines
12 KiB
C#
Raw Normal View History

2014-07-08 01:41:03 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Server.Implementations.Persistence;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Security
{
2016-02-14 05:32:19 +00:00
public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository
2014-07-08 01:41:03 +00:00
{
private readonly IServerApplicationPaths _appPaths;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
2016-06-11 15:55:05 +00:00
public AuthenticationRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector connector)
: base(logManager, connector)
2014-07-08 01:41:03 +00:00
{
_appPaths = appPaths;
2016-06-11 15:55:05 +00:00
DbFilePath = Path.Combine(appPaths.DataPath, "authentication.db");
2014-07-08 01:41:03 +00:00
}
2016-06-11 15:55:05 +00:00
public async Task Initialize()
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
using (var connection = await CreateConnection().ConfigureAwait(false))
{
string[] queries = {
2014-07-08 01:41:03 +00:00
2015-03-15 01:42:09 +00:00
"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)",
2016-06-11 20:12:01 +00:00
"create index if not exists idx_AccessTokens on AccessTokens(Id)"
2014-07-08 01:41:03 +00:00
};
2016-06-11 15:55:05 +00:00
connection.RunQueries(queries, Logger);
2015-03-15 01:42:09 +00:00
2016-06-11 15:55:05 +00:00
connection.AddColumn(Logger, "AccessTokens", "AppVersion", "TEXT");
}
2014-07-08 01:41:03 +00:00
}
public Task Create(AuthenticationInfo info, CancellationToken cancellationToken)
{
info.Id = Guid.NewGuid().ToString("N");
return Update(info, cancellationToken);
}
public async Task Update(AuthenticationInfo info, CancellationToken cancellationToken)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
cancellationToken.ThrowIfCancellationRequested();
2016-06-11 15:55:05 +00:00
using (var connection = await CreateConnection().ConfigureAwait(false))
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
using (var saveInfoCommand = connection.CreateCommand())
{
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)";
saveInfoCommand.Parameters.Add(saveInfoCommand, "@Id");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@AccessToken");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DeviceId");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@AppName");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@AppVersion");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DeviceName");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@UserId");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@IsActive");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DateCreated");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DateRevoked");
IDbTransaction transaction = null;
try
{
transaction = connection.BeginTransaction();
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
var index = 0;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
saveInfoCommand.GetParameter(index++).Value = new Guid(info.Id);
saveInfoCommand.GetParameter(index++).Value = info.AccessToken;
saveInfoCommand.GetParameter(index++).Value = info.DeviceId;
saveInfoCommand.GetParameter(index++).Value = info.AppName;
saveInfoCommand.GetParameter(index++).Value = info.AppVersion;
saveInfoCommand.GetParameter(index++).Value = info.DeviceName;
saveInfoCommand.GetParameter(index++).Value = info.UserId;
saveInfoCommand.GetParameter(index++).Value = info.IsActive;
saveInfoCommand.GetParameter(index++).Value = info.DateCreated;
saveInfoCommand.GetParameter(index++).Value = info.DateRevoked;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
saveInfoCommand.Transaction = transaction;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
saveInfoCommand.ExecuteNonQuery();
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
throw;
}
catch (Exception e)
{
Logger.ErrorException("Failed to save record:", e);
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
if (transaction != null)
{
transaction.Rollback();
}
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
}
2014-07-08 01:41:03 +00:00
}
}
}
2015-03-15 01:42:09 +00:00
private const string BaseSelectText = "select Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked from AccessTokens";
2014-07-08 01:41:03 +00:00
public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
2016-06-11 15:55:05 +00:00
using (var connection = CreateConnection(true).Result)
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
using (var cmd = connection.CreateCommand())
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
cmd.CommandText = BaseSelectText;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
var whereClauses = new List<string>();
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
var startIndex = query.StartIndex ?? 0;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
if (!string.IsNullOrWhiteSpace(query.AccessToken))
{
whereClauses.Add("AccessToken=@AccessToken");
cmd.Parameters.Add(cmd, "@AccessToken", DbType.String).Value = query.AccessToken;
}
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
if (!string.IsNullOrWhiteSpace(query.UserId))
2016-01-20 03:02:14 +00:00
{
2016-06-11 15:55:05 +00:00
whereClauses.Add("UserId=@UserId");
cmd.Parameters.Add(cmd, "@UserId", DbType.String).Value = query.UserId;
2016-01-20 03:02:14 +00:00
}
2016-06-11 15:55:05 +00:00
if (!string.IsNullOrWhiteSpace(query.DeviceId))
2016-01-20 03:02:14 +00:00
{
2016-06-11 15:55:05 +00:00
whereClauses.Add("DeviceId=@DeviceId");
cmd.Parameters.Add(cmd, "@DeviceId", DbType.String).Value = query.DeviceId;
2016-01-20 03:02:14 +00:00
}
2016-06-11 15:55:05 +00:00
if (query.IsActive.HasValue)
{
whereClauses.Add("IsActive=@IsActive");
cmd.Parameters.Add(cmd, "@IsActive", DbType.Boolean).Value = query.IsActive.Value;
}
2014-08-14 13:24:30 +00:00
2016-06-11 15:55:05 +00:00
if (query.HasUser.HasValue)
{
if (query.HasUser.Value)
{
whereClauses.Add("UserId not null");
}
else
{
whereClauses.Add("UserId is null");
}
}
var whereTextWithoutPaging = whereClauses.Count == 0 ?
2014-08-14 13:24:30 +00:00
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
2016-06-11 15:55:05 +00:00
if (startIndex > 0)
{
var pagingWhereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM AccessTokens {0} ORDER BY DateCreated LIMIT {1})",
pagingWhereText,
startIndex.ToString(_usCulture)));
}
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
var whereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
2014-08-14 13:24:30 +00:00
2016-06-11 15:55:05 +00:00
cmd.CommandText += whereText;
2014-08-14 13:24:30 +00:00
2016-06-11 15:55:05 +00:00
cmd.CommandText += " ORDER BY DateCreated";
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
if (query.Limit.HasValue)
{
cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(_usCulture);
}
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
cmd.CommandText += "; select count (Id) from AccessTokens" + whereTextWithoutPaging;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
var list = new List<AuthenticationInfo>();
var count = 0;
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
while (reader.Read())
{
list.Add(Get(reader));
}
if (reader.NextResult() && reader.Read())
{
count = reader.GetInt32(0);
}
2014-07-08 01:41:03 +00:00
}
2016-06-11 15:55:05 +00:00
return new QueryResult<AuthenticationInfo>()
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
Items = list.ToArray(),
TotalRecordCount = count
};
2014-07-08 01:41:03 +00:00
}
}
}
public AuthenticationInfo Get(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
2016-06-11 15:55:05 +00:00
using (var connection = CreateConnection(true).Result)
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
var guid = new Guid(id);
2014-07-08 01:41:03 +00:00
2016-06-11 15:55:05 +00:00
using (var cmd = connection.CreateCommand())
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
cmd.CommandText = BaseSelectText + " where Id=@Id";
cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = guid;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
2014-07-08 01:41:03 +00:00
{
2016-06-11 15:55:05 +00:00
if (reader.Read())
{
return Get(reader);
}
2014-07-08 01:41:03 +00:00
}
}
2016-06-11 15:55:05 +00:00
return null;
}
2014-07-08 01:41:03 +00:00
}
private AuthenticationInfo Get(IDataReader reader)
{
var info = new AuthenticationInfo
{
Id = reader.GetGuid(0).ToString("N"),
AccessToken = reader.GetString(1)
};
if (!reader.IsDBNull(2))
{
info.DeviceId = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
info.AppName = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
2015-03-15 01:42:09 +00:00
info.AppVersion = reader.GetString(4);
2014-07-08 01:41:03 +00:00
}
2015-03-15 01:42:09 +00:00
2014-07-08 01:41:03 +00:00
if (!reader.IsDBNull(5))
{
2015-03-15 01:42:09 +00:00
info.DeviceName = reader.GetString(5);
}
2016-02-14 05:32:19 +00:00
2015-03-15 01:42:09 +00:00
if (!reader.IsDBNull(6))
{
info.UserId = reader.GetString(6);
2014-07-08 01:41:03 +00:00
}
2015-03-15 01:42:09 +00:00
info.IsActive = reader.GetBoolean(7);
info.DateCreated = reader.GetDateTime(8).ToUniversalTime();
2014-07-08 01:41:03 +00:00
2015-03-15 01:42:09 +00:00
if (!reader.IsDBNull(9))
2014-07-08 01:41:03 +00:00
{
2015-03-15 01:42:09 +00:00
info.DateRevoked = reader.GetDateTime(9).ToUniversalTime();
2014-07-08 01:41:03 +00:00
}
2016-02-14 05:32:19 +00:00
return info;
2014-07-08 01:41:03 +00:00
}
}
}